- Home /
Question by
Kazuva · Apr 06, 2016 at 09:10 AM ·
scripting problemnot workingreferencingreference-other-object
how do i refer to a instantiated gameobject?
i can't find what is wrong whith my code
using UnityEngine;
using System.Collections;
public class pyssy : MonoBehaviour {
public Transform naali;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void ammu (int mia) {
Transform jousi = (Transform)Instantiate (naali, new Vector3(transform.position.x, transform.position.y , transform.position.z), transform.rotation);
print(jousi);
jousi.transform.GetComponent<nuoli>().nimea(mia);
print(mia);
}
}
NullRefereranceException: Object referance not set up to an instance of an object at line 22
Comment
Best Answer
Answer by Ckboyd89 · Apr 07, 2016 at 04:47 AM
It's usually a good idea to reference from and instantiate as GameObjects and then branch out to other components from there. Below are the changes that I would make:
public class pyssy : MonoBehaviour
{
public GameObject naali;
void Start ()
``{
ammu(0); // Test purposes, comment out
}
public void ammu (int mia)
``{
GameObject jousi = (GameObject)Instantiate (naali, new Vector3(transform.position.x, transform.position.y , transform.position.z), transform.rotation);
print(jousi);
// Using the transform to get a component is not necessary
// jousi.transform.GetComponent<nuoli>().nimea(mia);
jousi.GetComponent<nuoli>().nimea(mia);
print(mia);
}
}
that doesn't seem to make any difference "jousi.GetComponent().nimea(mia);" still doesn't work because: "NullRferanceexception: Object referance in not set to an instance of object"
$$anonymous$$ake sure that the prefab you are instantiating (naali) has a "nuoli" component attached to it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612074253im_/https://answers.unity.com/themes/thub/images/avi.jpg)