x


Sending C# commands to an OnTriggerEnter's collider object

I'm doing the Walker Boys Studio lab 2, part 33. But I'm writing all the scripts in C# to get that sweet auto-complete goodness.

The issue I'm running into occurs when the asteroid hits the player's shield. Pretty sure they're both set up right (a sphere with a sphere collider, IsTrigger=true, and a rigidbody).

Here's the code that runs for the asteroid:

void OnTriggerEnter(Collider other)
{
    if (other.tag == "shield")
    {
       HitShield(other.gameObject);
       ExplodeAsteroid();
       ResetPosition();
    }
}

void HitShield(GameObject other)
{
    scriptShield localShield = (scriptShield)other.GetComponent(typeof(scriptShield));
    localShield.HitShield();
}

The error I'm getting is NullReferenceException: Object reference not set to an instance of an object, which occurs when I try to call localShield.HitShield();. Does it matter that the shield object is a prefab which is instantiated by the player prefab?

How can the object be null if I can read its tags? There's something fundamental I'm missing, right?

more ▼

asked Aug 05 '11 at 12:10 AM

januskirin gravatar image

januskirin
1 1 1 1

(comments are locked)
10|3000 characters needed characters left

1 answer: sort oldest

The GameObject is not null, that's kinda impossible ;) I guess the Script component you're trying to access is not there. Keep in mind that "other" referes to a collider that is attached to an GameObject tagged "shield". Your script have to be attacht to the same GameObject.

Btw. there are generic versions of GetComponent, GetComponents and GetComponentInChildren that doesn't require you to cast the returnd type "manually":

scriptShield localShield = other.GetComponent<scriptShield>();

If your shild-script is attached to a child of the collider you can use

scriptShield localShield = other.GetComponentInChildren<scriptShield>();

also in such cases when you're not sure if the component is really there, you can do a check yourself:

scriptShield localShield = other.GetComponentInChildren<scriptShield>();
if (localShield != null)
{
    localShield.HitShield();
}
else
{
    Debug.LogWarning("Hit shield but no scriptShield found",this);
}
more ▼

answered Aug 05 '11 at 12:27 AM

Bunny83 gravatar image

Bunny83
45k 11 48 206

Damn, my first question and it's a "you forgot to link the script to the prefab" error. That was my mistake. Thanks, Bunny83. I'll pay more attention from now on. :-)

Aug 05 '11 at 01:09 AM januskirin
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2483
x394
x334
x9

asked: Aug 05 '11 at 12:10 AM

Seen: 1757 times

Last Updated: Aug 05 '11 at 01:34 AM