Hi. I’ve been trying to get my script working for a while. I’m by no means a good coder, but I can usually get UnityScript to do what I want it to. The following script has no errors or warnings; it just doesn’t do what it should. I’m trying to use a GetComponent to increase my remaining ammunition variable (lasersLeft) in the script CreateLaser by one. I need to get this script to work. Any help is appreciated. Thanks.
var createLaser : CreateLaser;
createLaser = GetComponent("CreateLaser");
function onTriggerEnter(other : Collider){
if (other.gameObject.tag == "Diamond"){
createLaser.lasersLeft +=1;
Debug.Log (createLaser.lasersLeft);
}
Destroy (gameObject);
}
OnTriggerEnter not onTriggerEnter
That was the problem.
(I said I’m not much of a coder). That fixed one problem, but created another. Now when the laser (what this script is attached to) hits the Diamond it gives me the error: NullReferenceException: Object reference not set to an instance of an object
It still isn’t working. I’ve made sure the variable I’m trying to access is public. I’ve made sure the GameObject is tagged “Glider.” I’ve tried GameObject.Find and GameObject.FindWithTag to no avail. What’s wrong with this script?
var LaserScript : CreateLaserScript;
function Start(){
LaserScript = GameObject.FindWithTag("Glider").GetComponent("CreateLaserScript");
}
function OnTriggerEnter(other : Collider){
if (other.gameObject.tag == "Diamond"){
LaserScript.GainLaser();
}
Destroy (other.gameObject);
Destroy (this.gameObject);
}
Maybe because you destroyed the object???
That isn’t it. I tried taking them out and it still didn’t work. Anyway, the Destroy happens after the GainLaser. The GainLaser function isn’t on the object that has collided. It’s n an object that has nothing to do with the collision other than the fact that it has a script where a function needs to be executed.
Here’s my current script, still not working.
var LaserScriptObject : GameObject;
var LaserScript : CreateLaserScript;
function Start(){
LaserScriptObject = GameObject.FindWithTag("Glider");
LaserScript = LaserScriptObject.GetComponent("CreateLaserScript");
}
function OnTriggerEnter(other : Collider){
if (other.gameObject.tag == "Diamond"){
LaserScript.lasersLeft -= 1;
Destroy (other.gameObject);
Destroy (this.gameObject);
}
}
Is FindWithTag returning a GameObject? Is GetComponent returning the script?
FindWithTag is returning a GameObject. GetComponent is not returning a script.
I fixed it. I was looking and realized that it wasn’t “Glider” that had “CreateLaserScript” but two of its children. My working script:
var LaserScriptObject : GameObject;
var LaserScript : CreateLaserScript;
function Start(){
LaserScriptObject = GameObject.Find("Laser fire");
LaserScript = LaserScriptObject.GetComponent("CreateLaserScript");
}
function OnTriggerEnter(other : Collider){
Debug.Log ("Hit");
if (other.gameObject.tag == "Diamond"){
LaserScript.GainLaser(1);
Destroy (other.gameObject);
Destroy (this.gameObject);
}
}