I am trying to get a script of intractable object e.g. a button or a lever.
The thing is that there might be a different script to each of these objects.
So i need to set a type of a script like “InteractableScript” to enable this specific script and not asking an if inside an if…
Is there a way to do that?
Tx.
Ethan.
EDIT:
To be more specific and not confuse people:
What i want to do is like so:
this.GetComponent<>(MonoDevelop);
But this will get me all the monodevelop scripts.
I want to get all the “Interactable” scripts.
I have made a base class called InteractableObject, and two subclasses inheriting from this calss: InteractableWaffle and InteractableChocolate. These are added to a List.
using UnityEngine;
using System.Collections.Generic;
public class InteractableContainer : MonoBehaviour {
public List<InteractableObject> interactableObjects;
void Start()
{
foreach (InteractableObject obj in interactableObjects)
{
Debug.Log(obj.GetType().Name);
if (obj.GetType() == typeof(InteractableWaffle))
Debug.Log("Waffle!");
else if (obj.GetType() == typeof(InteractableChocolate))
Debug.Log("Chocolate!");
}
}
}
/// IRunable interface, allow to use Run() method in any class what extends it.
public interface IRunable
{
public void Run();
}
/// You can extend any class with IRunable interface (this is example class name).
/// Example: This script can be attached to the doors
public class Doors : MonoBehaviour, IRunable
{
/// You must override the Run() method here
public void Run()
{
Debug.Log("OPENING DOORS");
}
void Update()
{
}
...
}
/// Switch class keeps IRunable implementation as handler.
/// You need to put the RunnableObject in inspector only, or make some game logic here.
/// Example: This script can be attached to the switch object.
public class Switch : MonoBehaviour
{
/// IRunable implementation handler, Unity not support interface property fields in inspector so we will cast it later.
public MonoBehaviour runableObject;
/// Execute this method to run the RunableObject Run() method.
public void Switch()
{
if(runableObject != null && runableObject is IRunable)
((IRunable)runableObject).Run();
}
/// Simple example of switch on trigger enter
void OnTriggerEnter(Collider col)
{
if(col.tag == "Player")
{
Switch();
}
}
}