- Home /
C# Interacting scripts via GetComponent
I am kind of new to unity and I have a problem with GetComponent...
I want a door to open when my Player hits a cube tagged "SwitchTag" with a boolean:
(Main Script:)
[...]
OnCollisionEnter (Collision collision){
if (collision.gameObject.tag == "SwitchTag")
{
DoorTutorial.GetComponent<DoorSwitch>().SwitchOn = true;
sfx_door.Play();
}
}
(Door Script:)
public class DoorSwitch : MonoBehaviour {
public bool SwitchOn;
private Vector3 startPos;
// Use this for initialization
void Start () {
startPos = transform.position;
SwitchOn = false;
}
// Update is called once per frame
void Update ()
{
if(SwitchOn)
{
transform.Translate (0, 0, 3 * Time.deltaTime);
if (transform.position.z > startPos.z + 1)
SwitchOn = false;
}
}
}
But it doesn't work ...
Any help would be appreciated :)
How have you declared and initialized 'DoorTutorial' in the first script? When you say 'doesn't work' are you having a compiletime error, runtime error, or it just doesn't do anything?
I had this: NullReferenceException: Object reference not set to an instance of an object
And the door did not move
To make the hole thing a bit clearer:
I have tried to activate the boolen wit a $$anonymous$$ey ins$$anonymous$$d of a collison, just to look if it works:
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Q))
{
//if (hit.gameObject.CompareTag("SwitchTag")){
TuerTutorial.GetComponent<TuerSwitch>().auf = true;
sfx_grenze.Play();
}
But it still doesn't work
Answer by aldonaletto · Dec 15, 2013 at 03:41 PM
Are you having any errors with GetComponent? Null Reference errors, for instance? If the code simply doesn't work, the reason probably is the OnCollisionEnter nature: this event is generated when a Rigidbody hits a collider - if the player is a CharacterController or a simple collider, OnCollisionEnter never gets called.
If the player is a CharacterController, use OnControllerColliderHit instead:
void OnControllerColliderHit(ControllerColliderHit hit){
// CompareTag is more efficient than direct tag comparison:
if (hit.gameObject.CompareTag("SwitchTag")){
DoorTutorial.GetComponent<DoorSwitch>().SwitchOn = true;
sfx_door.Play();
}
}
Thank you!
Yes I had these errors, that is fixed now... I have the sound effect on collision in to be sure that it works, but now when i hit the Tagged cube nothing happens... and the door stays closed as well
Your answer
![](https://koobas.hobune.stream/wayback/20220613124224im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Store Multiple values in one variable 2 Answers
Time based score system? 2 Answers
Booleans problem 1 Answer
More simple code not working 1 Answer