x


NullReferenceException using CompareTag

Can't figure out what I'm doing wrong here but it keeps coming up with a NullReferenceException error on the CompareTag line. Maybe I'm using it incorrectly? Have tried everything.

function OnTriggerStay(other : Collider) {
    if (!other.transform.parent.CompareTag("Player")) {
       Debug.Log("something other than player");
    }
}
more ▼

asked Mar 27 '12 at 09:56 AM

Essential gravatar image

Essential
480 48 65 79

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

3 answers: sort newest

You're trying to access the parent of a GameObject which does not have a parent. Check if it has a parent and then compare the tag. Try this:

function OnTriggerStay(other : Collider) 
{
    if (other.transform.parent && !other.transform.parent.CompareTag("Player")) {
       Debug.Log("something other than player");
    }
}
more ▼

answered Mar 27 '12 at 10:26 AM

farooqaaa gravatar image

farooqaaa
416 2 5 8

Solves the error. Though now doesn't work as intended (needs to trigger for everything, not just objects with parents) — will have to investigate another method. Thanks.

Mar 27 '12 at 10:25 PM Essential
(comments are locked)
10|3000 characters needed characters left

Does your GameObject with collider, got a parent with tag player? maybe try to put to your object the tag Player not at your parent, and then, if (!other.CompareTag ("Player")) { Debug.Log("something other than player"); }

in your exemple, if an object, without parent stay in your trigger, it will cast an NullReferenceException. I think

more ▼

answered Mar 27 '12 at 11:25 AM

Viluredfish gravatar image

Viluredfish
65 1 1 4

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

I think that should be

if (other.transform.parent.CompareTag!=("Player")) {
more ▼

answered Mar 27 '12 at 10:21 AM

AtomicHippo gravatar image

AtomicHippo
51

Apologies for this answer, I somehow managed to overlook the parent reference in your code:(

Mar 27 '12 at 10:51 AM AtomicHippo

That's okay, thanks for trying. :)

Mar 27 '12 at 11:07 AM Essential

Took back my downvote. Please check your code before posting an answer.

Mar 27 '12 at 12:03 PM farooqaaa
(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:

x396
x50
x9

asked: Mar 27 '12 at 09:56 AM

Seen: 396 times

Last Updated: Mar 27 '12 at 10:25 PM