Hey guys! Have this error, and just can’t get what i’ve done wrong.
I’ve read some articles about the same problem, carefully inspect my code, but still cant get it. Please, help
“NullReferenceException: Object reference not set to an instance of an object
CubeEditor.Start () (at Assets/CubeEditor.cs:16)”
So, here’s the script itself:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class CubeEditor : MonoBehaviour
{
[SerializeField] [Range(1f, 20f)] float gridSize = 10f;
TextMesh textMesh;
void Start()
{
textMesh = GetComponentInChildren<TextMesh>();
textMesh.text = "TEST";
}
void Update()
{
Vector3 snapPos;
snapPos.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize;
snapPos.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize;
transform.position = new Vector3(snapPos.x, 0f, snapPos.z);
}
}
for some reason your image isn’t showing so I’m left with suggesting that you may want to check your Heirarchy, do you have a TextMesh component attached to a child object of the object your script is attached to? Also, I’ll note that I’ve experienced a lot of issues with referencing components through Code due to Unity running scripts before completely loading the scene.
Hey! I’ve started from scratch and have the same result
This NullReferenceException is not bothering me now, just cant get the script and scene work
But i’ve just copy-pasted anything… what could gone wrong?
Here’s updated script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
[SelectionBase]
public class CubeEditor : MonoBehaviour
{
[SerializeField] [Range(1f, 20f)] float gridSize = 10f;
TextMesh textMesh;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 snapPos;
snapPos.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize;
snapPos.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize;
transform.position = new Vector3(snapPos.x, 0f, snapPos.z);
textMesh = GetComponentInChildren<TextMesh>();
textMesh.text = snapPos.x / gridSize + "," + snapPos.z / gridSize;
}
}
Also i restarted unity a few times, but result is the same
The “XX,XX” is not changing to coordinates, dunno why.
Tryed to change the position of cube, same result - text is still XX,XX
Here is a two screenshot of unity scene and game windows
Do you know what is causing that NullReferenceException? If not, try to figure that out because it might be the reason why your script and your scene do not work as intended.
Furthermore, please elaborate a bit further on what your goal is. Without knowing what you tied to achieve, it is impossible to provide a “fix”.
I actually meant your specific problem because “what could gone wrong” is meaningless for us without knowing what your want to achieve in this particular case.
I’m glad you found the problem and fixed it. Well done!