- Home /
Accessing a GameObject from another script
Hello,
I am trying to access a GameObject(Clone) from another script. I get the error:
NullReferenceException: Object reference not set to an instance of an object
Unit.Start () (at Assets/Unit.cs:28)
The semi-abridged code can be seen below, one script for a Spawner that creates clones of prefab'd units, the other a class to hold details on the Units :
Script SpawnUnits.cs
public class SpawnUnits : MonoBehaviour
{
public GameObject[] Units;
public static int? selectColor = null;
public GameObject newUnit;
void Awake ()
{
NewUnit();
}
public int NewUnit()
{
selectColor = Random.Range(0, 4);
newUnit = Instantiate(Units[(int) (selectColor)], transform.position, Quaternion.identity);
int? selectColor1 = (selectColor);
return (int)selectColor1;
}
}
Script Unit.cs
public class Unit : MonoBehaviour {
public GameObject SpawnGameObject;
private SpawnUnits SpawnScript;
public Transform t;
[System.NonSerialized]
public int TileColor;
// The point around with the game pieces rotate
public Vector3 rotationPoint;
// How fast the piece floats up naturally (with no key presses)
public float floatTime = 0.8f;
void Awake ()
{
// t = GetComponent<Transform>();
}
void Start ()
{
SpawnScript = SpawnGameObject.GetComponent<SpawnUnits>();
Debug.Log(SpawnScript);
t = SpawnScript.newUnit.transform;
}
}
Debug logs show SpawnScript as null, therein not picking up the reference properly. I'm trying to store the transform of these GameObject clones, but to no avail. I'm having awful difficulty understanding how to properly build out inter-script relationships, so any help is appreciated!
Im just going to focus on the start function for now. In the first line you try to set "SpawnScript" to a component taken from "SpawnGameObject". What could go wrong: A. SpawnGameObject is not assigned (this would throw a null reference exception). B. SpawnGameObject doesnt have a component SpawnUnits so it returns null. If the Debug.Log() already gives null, the problem is above that Debug.Log().
Answer by Zentiu · Mar 20, 2020 at 01:21 AM
Tell me if im wrong but i am assuming that the unit script is attached to the unit gameobject you spawn with the spawnunits script. Since you already get a reference of the new unit during instantiation (newUnit = Instantiate(Units[(int) (selectColor)], transform.position, Quaternion.identity);) There you could reference the script like:
newUnit.GetComponent<Unit>().t = newUnit.transform;
Metalted is correct. You need to set the SpawnGameObject. SInce the new unit is probebly a prefab that got instantiated it will not hold a reference to spawnGameObject since prefabs dont hold any references that are in the hierarchy of your scene unless its part of the prefab itself. You can look for the gameobject with the 'SpawnUnits' through tags or gameobject.find. The code in awake of your unit script should also work or just move it to the start method.