- Home /
After instantiating an object I cannot refer to it?
public Transform prefab;
GameObject target;
void Start () {
teksture = Instantiate(prefab, new Vector2(transform.position.x, transform.position.y), Quaternion.identity)as GameObject;
}
void Update () {
teksture.transform.position = transform.position;
}
"NullRefrenceExeption: Object reference not set to an instance of an object"
What am I doing wrong? The project is in 2D. The script doesn't notice it out side of Start function. EDIT: I added prefab I just drag and drop the prefab into place in unity. And also now I noticed that if I instantiate teksture in update function and try to call it in any way, it gives the same error. Also I should say that it does spawn it.
You've only given us part of the script and don't give us info about the error. How is 'prefab' declared? How is 'prefab' initialized? How is 'teksture' declared? If you put a 'Debug.Log(teksture)' just below line 4, does it show a null value or is it being initialzied?
Have you declared teksture anywhere in your code.?
Answer by haim96 · Dec 12, 2013 at 09:05 AM
"public Transform prefab; " should be -> "public GAMEOBJECT prefab;"
if you instantiate prefab it need to be gameobject type not transform.
Actually, you can instantiate from many components : transform, rigidbody, scripts, etc etc.
The problem is as stated by robertbu : teksture is not declared as a variable, where it should be declared as a global variable.
ohhh... O$$anonymous$$. i never tried it before. good to know!
Great! If you really can instantiate from transform I think it didn't worked for you because you tried to instantiate as gameobject ins$$anonymous$$d of transform. In other words you tried to convert transform type to gameobject type.
Answer by lighting · Dec 12, 2013 at 08:14 AM
The problem is that Instantiate() method didn't work and returned null. Thus teksture is null.