- Home /
Duplicate Question
NullReference with trigger C# ?
Hi,
I don't understand why I get this error in my code :
CornerIA1.OnTriggerEnter After the collision, triggerOn = true should be sent to the IAParent script, the scripts are well connected to their gameObject, I also tried with GetComponent<> or transform.GetComponent... but still the same thing. Here is the code : //IAParent scr; void Start () { }NullReferenceException: Object reference not set to an instance of an object
void Update () { }
void OnTriggerEnter ( Collider other ) { IAParent scr = other.GetComponent("IAParent") as IAParent; scr.triggerOn = true;//null reference } Would you know why? Thanks
"other" isn't a GameObject, and it migth be to do what you want. try other.gameObject.GetComponent("IAParent") as IAParent;
. about the GetComponent method I prefer doing GetComponent() , works better
@Ninita thanks, unfortunately no. It still shows the error on scr.triggerOn... if I remove it, I don't get the error anymore.
do
IAParent scr = other.gameObject.GetComponent<IAParent>();
if(!scr)
{
Debug.Log("scr don't exist");
scr = other.gameObject.AddComponent("IAParent");
}
scr.triggerOn=true;
that error says that gameObject with that collider don't have any component IAParent, and with this code you guarantee it have
Answer by Karsten · May 11, 2013 at 07:19 AM
not tested
what happens if you use something like this?
//IAParent scr;
void Start () { }
void Update () { }
void OnTriggerEnter ( Collider other ) {
IAParent scr = other.gameObject.GetComponent("IAParent") as IAParent;
scr.triggerOn = true;//null reference
}
Thanks @$$anonymous$$arsten, nop, I tried this first. I still get the same error on scr.triggerOn = true ... @Fattie sorry maybe there is a mistake with the closure of this topic, could you re-open it? it works fine for "scr = ..." but it does not work with "src.triggerOn..." . triggerOn is "public" in my other class. Thanks
hm very strange, can you proof that scr has a value after IAParent scr = other.gameObject.GetComponent("IAParent") as IAParent; ? also i think you can left out "as IAParent" because its implicit said in the declaration IAParent scr =
maybe triggerOn is a local variable in IAParent?
Thanks @$$anonymous$$arsten for your help, I could make it work with Ninita's code, thanks anyway. Really appreciated!