- Home /
How would I get different references to scripts depending on what object it is attached to?
In my game I'm making it so that I have one master ActionButtonScript script that I attach to each "action item" (Doors, lockers, buttons, anything you can interact but not pick up or bring with you). Each different action item has a different script that will do whatever that item does, but it gets activated by the ActionButtonScript (It inherits from a different ActionScript class that has an Action function).
My problem is that I can only make ActionButtonScript reference one script, and need it to references other scripts depending on what object it is attached to. Is there an easy way for me to do this, or am I going to have to make a new script for each different object? Or am I going about this in a completely wrong/terribly inefficient manner, and how should I do it instead? Thank you
public class ActionButtonScript : MonoBehaviour
{
/*I want this code to be applied to all items with the "Action Items" Tag*/
public GameObject player, actionItem;
public ActionScript actionScript; //ActionScript is a parent class, in this case to FootlockerOpenerScript
public float maxDistance = 4;
CrossHairScript crossHairScript;
float distance;
bool canDoAction;
void Start ()
{
player = GameObject.Find("Main Camera");
crossHairScript = player.GetComponent<CrossHairScript>();
actionItem = gameObject;
actionScript = actionItem.GetComponent<FootlockerOpenerScript>(); //I need to make actionScript reference whatever the objects unique script is
}
void Update ()
{
if(canDoAction && Input.GetKeyDown(KeyCode.E))
{
actionScript.Action();//inheierted from ActionScrip
}
}
/*Other code*/
}
Answer by hiddenspring81 · May 25, 2013 at 09:08 PM
Couldn't you just change it to
actionScript = actionItem.GetComponent<ActionScript>();
Since they all share a common base type, in this case, ActionScript
.
Wow, thank you, this worked perfectly! I didn't bother doing that because I figured it wouldn't work properly since I never attached ActionScript to anything, guess I have to brush up on my C# inheritance.
Your answer
