- Home /
Getting NullReference when calling Instantiate from another script
Hi All – Need the help, please!
New to unity and I have run into the dreaded
“NullReferenceException: Object reference not set to an instance of an object
What I am trying to do is instantiate a Gameobject within an array from another script. Code snip it below
code is in C# (ScriptGame)
using UnityEngine;
using System.Collections;
public class ScriptGame : MonoBehaviour {
public GameObject [] cube;
public float playTime = 0.0f;
public float delayTime = 0.0f;
public float delayAmount = 0.0f;
public bool timeActive = true;
private float xOriginalpos;
private float xOffsetpos = -3.8f;
// Update is called once per frame
void Update (){
if (timeActive)
{
playTime = Time.time;
}
if (playTime > delayTime)
{
delayAmount = Random.Range(4,8);
delayTime = Time.time + delayAmount;
xOriginalpos = Random.Range(0,10);
spawn ((xOffsetpos + xOriginalpos) , 19.0f);
Debug.Log ("Delayed of " + delayAmount + "Seconds");
}
}
public void spawn(float x, float y){
Instantiate (cube[Random.Range(0, cube.Length)],new Vector3(x, y, 9.0f), Quaternion.identity);
}
}
Then from the other script (scriptBlock.cs) I try call "spawn" after confirming the correct Gameobject was hit using RayCast.
public void changecolor (){
if (Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out colorHit, rayDistance)){
if (((colorHit.transform.tag == "BLUE") || (colorHit.transform.tag == "CYAN" )) && (colorHit.transform.position.y > 2.68f)){
//Debug.Log ("Hitcolor");
ScriptGame other;
other = gameObject.GetComponent("ScriptGame") as ScriptGame;
other.spawn(3.8f, 19.0f);
}
}
}
}
When I click on the object attached to the above script (scriptBlock.cs)) I get
NullReferenceException: Object reference not set to an instance of an object scriptBlock.changecolor () (at Assets/Scripts/scriptBlock.cs:131) scriptBlock.Update () (at Assets/Scripts/scriptBlock.cs:32)”
the error points to the following line
other.spawn(3.8f, 19.0f);
I am not sure how to fault find this issue. I think it has something to do with the cube array (but it is populated with prefabs correctly)
All help appreciated
Thank you