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 :slight_smile:

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();
    }
}