Ok, so I read through a bunch of the previous posted questions concerning this topic, but none of them really answered my question.. I'm extremely new to Unity and C#... What I am trying to do is open a door via an animation when the player approaches it. I have the doors already animated, and its under the door object when i expand it. How do I go about writing the right script, and setting up the colliders and what not that is needed? If anyone can help me you'd be a life saver.
may i suggest using java script instead? it's alot easier especially if your new to scripting or you already know actionscript. it may look something like this (assuming you want the door to open and stay open)
var door : GameObject;
private var HasBeenTriggered : int;
HasBeenTriggered = 0;
function OnTriggerEnter (collision : Collider)
{
if (collision.gameObject.tag == "teaPot")
{
if(HasBeenTriggered == 0)
{
door.animation.Play ();
HasBeenTriggered = 1;
}
}
}
Here's a C# script that opens a door. Once it's triggered the script deletes itself. In my case the animation to open the door is named "open". Make sure the `WrapMode` of your animation is set to `Once`. That way the door stays open. This script have to be attached to a GameObject that act as trigger. Add a collider, eg. BoxCollider to this GameObject, set it's isTrigger property and place it in front of the door. You have to drag&drop your animated door onto the animatedDoor variable of the script.
In C# (and also in JS) it's the scriptfiles name that have to be equal to the classname. In JS you can omit the class header and JS will automatically inherit from MonoBehaviour.
using UnityEngine;
using System.Collections;
public class OpenDoor : MonoBehaviour
{
public Animation animatedDoor = null;
void Start()
{
if (animatedDoor == null)
Destroy(this); // The script needs the variable to be set
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
animatedDoor.Play("open");
Destroy(this); // when triggered remove this script
}
}
}
If you need more complex doors (eg. that closes automatically and so on) that involves a bit more logic in the script. Make yourself familiar with the Unity-api. Unity is very well documented, so take a look at the scripting reference and the runtime classes to understand the concept of Unity.