- Home /
NullReferenceException with SwitchController script
My script wont seem to be working and I dont know why. It is supposed to tick whether your able to mount or not. If you are, and you press F, it should parent the player to the riderPivot and reset its position. Its also supposed to disable player movement and enable horse movement. But all I get when trying to do it is NullReferenceException: Object reference not set to an instance of an object. Any help is appreciated!!!!
Heres my script
using UnityEngine; using System.Collections;
public class SwitchController : MonoBehaviour { public bool mounted; public bool mountable; public Transform riderPivot; private GameObject rider;
void OnTriggerEnter(Collider rider)
{
if (rider.tag == ("Player")) {
mountable = true;
}
else
{
mountable = false;
}
}
void OnTriggerExit(Collider rider)
{
mountable = false;
}
void Update () {
if (mountable == true && Input.GetKey (KeyCode.F)) {
mounted = true;
Mount ();
}
if (mounted == true && Input.GetKey (KeyCode.F)) {
mounted = false;
UnMount ();
}
}
void Mount(){
rider.transform.position = riderPivot.position;
rider.transform.SetParent (riderPivot);
rider.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonUserControl> ().enabled = false;
this.GetComponentInParent<Horse> ().enabled = true;
}
void UnMount(){
rider.transform.position = this.transform.position;
rider.transform.SetParent (null);
rider.GetComponent<UnityStandardAssets.Characters.ThirdPerson.ThirdPersonUserControl> ().enabled = true;
this.GetComponentInParent<Horse> ().enabled = false;
}
}
Answer by Acid_kenobi · Sep 06, 2016 at 04:52 AM
Looks like you're not setting a reference to the rider gameobject. Easiest way would be make it public not private and assign it in the inspector. Or use a GetComponent call in a start function
Your answer
Follow this Question
Related Questions
Moving child transform also moves parent rigidbody 0 Answers
Child object getting transformed out side the scene on collision? 1 Answer
Child instantiated object to RayCastHit's parent. 1 Answer
Object changes position/rotation, when moved (in/out of parent) in the heirarchy in the editor! 0 Answers