- Home /
Accessing Variable From Other Gameobject
Ok so I was hoping that when these to objects go collide or in my case enter trigger that they roll a dice and which ever is lower it gets deleted! Here my code.
#pragma strict
var Dice = 0;
Dice = Random.Range(1,100);
private var anotherScript : SunDele;
function OnTriggerEnter(slr : Collider) {
anotherScript = slr.GetComponent(SunDele);
if (anotherScript.Dice > Dice) {
Destroy (gameObject.transform.parent.gameObject);
}
}
Now I have put rigedbody on both and enabled trigger enter but I get the error: NullReferenceException: Object reference not set to an instance of an object SunDele.OnTriggerEnter (UnityEngine.Collider slf) (at Assest/SunDele.js:8) However it did do what I wanted it to do (I can see through the editor) but it pause the game and gives me that error. plz help
I see nothing wrong with your code or your setup. Put a Debug.Log() between line 5 and 6 to see if OnTriggerEnter() is being called.
I put a debug.log(anotherScript); on line 9 and when I it, it does show me the numbers but still also give me errors :( In the scene view it works but that error pause the game . . . and if I unpause then when I export the game it will be buggy
You need to tell us what error on what line. Paste a copy of the error from the console into a comment. I'll bet is is line 8. You would get this error if whatever triggered the collider did not have a 'SunDele' component.
You could modify line 8 to:
if (anotehrScript != null && anotherScript.Dice > Dice) {
Another common solution would be to give all of your 'Dice' objects the same tag and then check the tag before going to the trouble of GetComponent().
NullReferenceException: Object reference not set to an instance of an object SunDele.OnTriggerEnter (UnityEngine.Collider slf) (at Assest/SunDele.js:8)
I think the error is becuase of this e.g. cube1 cube 2 cube 3. cube 1 rolls a dice with cube2 and cube 3 rolls a dice with cube1. cube1 gets deleted and then cube3 can't get compent for the dice as cube1 is gone. I think that could be what is causing the error
Answer by SilentSin · Jul 27, 2014 at 02:25 AM
Edit: looks like line numbering is 1 indexed rather than 0 indexed, so the error line would actually be:
if (anotherScript.Dice > Dice) {
This means that anotherScript is null, which means that there isn't a SunDele script on the collider that entered the trigger. If you change it to:
if (anotherScript != null && anotherScript.Dice > Dice) {
Then it will do nothing when a collider without the script enters the trigger, and it will do what you want it to when a collider with the script enters.
Also, on this line:
Destroy (gameObject.transform.parent.gameObject);
The first reference to gameObject is useless, you could just have:
Destroy (transform.parent.gameObject);