enabling a script with a trigger...please help

Sorry in advance ,I looked all day in Unity Answers and on the forums but could not find the answer I’m looking for.

All I want to do is activate a script that is attached to an object when the player enters the trigger, and disable it when the player leaves the trigger.

This is the script I am tying to use to enable the script:

using UnityEngine; using System.Collections;

public class scripttrigger : MonoBehaviour {

void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == “Player”)
{
ConstantRotate ConstantRotate = other.gameObject.GetComponent();
ConstantRotate.enabled = true;
}
}

void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == “Player”)
{
ConstantRotate ConstantRotate = other.gameObject.GetComponent();
ConstantRotate.enabled = false;
}
}

}

However I keep getting this error message :

NullReferenceException: Object reference not set to an instance of an object
scripttrigger.OnTriggerEnter (UnityEngine.Collider other) (at Assets/scripttrigger.cs:12)

I have the “scripttrigger” script attached to a cube which is set as a trigger and the object is parented to the trigger cube. The “ConstantRotate” script is attached to both the cube and the object and unchecked/disabled on both.

Can anyone please help me figure out what I’m doing wrong?

It sounds like you are trying to activate the script on the object entering the trigger when you want to be doing it to the trigger.

other.gameObject.GetComponent<ConstantRotate>(); // instead of this
gameObject.GetComponent<ConstantRotate>();// try this

OMG!! That worked!! Thank you so much. I really appreciate your help. :slight_smile: thanks again!

1 Like

Ok so I’m trying to us pretty much the same script to call on a different script for another object. the code looks like this:

using UnityEngine;
using System.Collections;

public class coastertrigger : MonoBehaviour {

void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag==“Player”)
{
splineMove splineMove=gameObject.GetComponent();

splineMove.enabled=true;
}
}

void OnTriggerExit(Collider other)
{
if(other.gameObject.tag==“Player”)
{
splineMove splineMove=gameObject.GetComponent();
splineMove.enabled=false;
}
}

}

but it keeps telling me:

Assets/coastertrigger.cs(20,25): error CS0246: The type or namespace name `splineMove’ could not be found. Are you missing a using directive or an assembly reference?

Any idea why it’s not working for calling on this script? What am I doing wrong?

I get compiler errors with any other script is called on but “ConstantRotate” can anyone help please me figure out why it wont work with other scripts?