- Home /
I'm having trouble referencing a function from one script inside another
I trying to set up a script that keeps track of the hit points for bricks that are hit by a cannonball. I set it up using 2 scripts, one for the bricks (the script is attached to a prefab of the bricks) that keeps track of a hit point variable, and a second for the cannonball (attached to the prefab of the cannonball being instantiated). The cannonball script is supposed to call the brick script and update the HP if it detects collision with a brick.
Right now, it seems to be able to detect collision just fine, but I'm having difficulty getting the 1st script to call the second. I keep getting a null reference error saying that the object reference is not set to an instance of the object, an I'm not sure why. I dragged the game objects into the correct place in the inspector for both scripts. Am I doing something wrong?
This is my BrickHP.js:
var normalBrick : GameObject;
var crackedTexture: UnityEngine.Texture;
var hitPoints : float = 100;
function Start(){
}
function checkHP() {
if (hitPoints <= 50){
renderer.material.mainTexture = crackedTexture;
}
if (hitPoints <= 0) {
Destroy(normalBrick);
}
Debug.Log("I hit it");
}
And this is my cannonball script:
var normalBrick : GameObject;
var cannonball: GameObject;
function Start () {
}
function Update () {
}
function OnCollisionEnter(collision : Collision){
if(collision.gameObject.name == "Small Brick"){
Debug.Log(collision.gameObject.name);
var brickHP: BrickHP = GetComponent(BrickHP);
brickHP.checkHP();
}
}
I'll finish the rest of the code for calculating the actual HP later. Right now I'm just trying to figure out if I'm calling the script correcly.
http://docs.unity3d.com/Documentation/ScriptReference/
see the two "Accessing" links on the left hand side ...
Answer by whydoidoit · Oct 09, 2012 at 07:22 AM
You need to call the GetComponent on the thing you hit I'd guess...
var brickHP = collision.gameObject.GetComponent(BrickHP);
I tried to do this and Unity would not build the code
It isn't compiling correctly. This is what I put, but it gives me a message saying it is expecting a ;
function OnCollisionEnter(collision : Collision){
if(collision.gameObject.name == "Small Brick"){
Debug.Log(collision.gameObject.name);
var brickHP: collision.gameObject.GetComponent(BrickHP);
brickHP.checkHP();
}
}
It should be an = not a : between the definition and the assignment.
Haha well I guess it helps if your syntax is correct! That fixed it, thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613082059im_/https://answers.unity.com/themes/thub/images/avi.jpg)