-2
\$\begingroup\$

I set the trigger

 void OnTriggerStay(Collider other)
{

    other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);


}

But when player walks on, I got console warning

    NullReferenceException: Object reference not set to an instance of an object

I have set Rigidbody on the player.

How to make player be affected by trigger ?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Note that OnTriggerStay triggers when any game object with a collider (on one of the physics layers which collide with that of this object) collides with the object. You might be registering a collision with something other than the player. So you should check if the object you are colliding with is actually the player. A good way to do this is to set the tag of your player object to "Player" and then check for that tag in the collision method:

void OnTriggerStay(Collider other)
{
    if (other.gameObject.tag == "Player")
    {
        other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);
    }
}

When you still get that error instead of the expected results, then the most likely explanation is that you think you added a rigidbody to your player, but you actually didn't. In that case please edit the question with some screenshots which show how your player object looks in the inspector.

\$\endgroup\$
5
  • \$\begingroup\$ Ok, thank you. But now the problem is that Main camera which is child of the Player does not get affected by AddForce. So, Player still doesn't move up. \$\endgroup\$
    – eon
    Aug 30, 2018 at 22:43
  • \$\begingroup\$ @eon When the camera is a child of the player, then it should move when the player moves. If you added a rigidbody to your camera, you should remove it. There is generally no reason to add a rigidbody to an object which is not supposed to have a physical presence in the game. \$\endgroup\$
    – Philipp
    Aug 31, 2018 at 6:38
  • \$\begingroup\$ I removed it it now. Player still doesn't move. \$\endgroup\$
    – eon
    Aug 31, 2018 at 7:31
  • 1
    \$\begingroup\$ @eon this is not a problem we can diagnose & troubleshoot with the information you've given us so far. Try asking a separate question, including all the details we'd need to reproduce your scene and player control ourselves, so we can directly observe the problem. \$\endgroup\$
    – DMGregory
    Aug 31, 2018 at 13:30
  • \$\begingroup\$ Ah, I understand now what is the problem. I will make seperate question. \$\endgroup\$
    – eon
    Sep 3, 2018 at 16:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .