I have simple button script(in game, not gui button)
public GameObject target;
void Button()
{
target.SendMessage("Activate", SendMessageOptions.DontRequireReceiver);
}
If I drop in the inspector gameobject into “target” position with script containing “Activate” method it will work perfectly fine. No mater if it will be door, light, enemy spawner etc. So it works exactly as I want it to work.
The problem is that it uses SendMessage function which is much slower that the direct reference to the script and it is advised not to use it.
Therefore my question: is there a neat way to do it with direct reference to such many different types of objects, with drag and drop functionality.
If you have many objects and different scripts (let’s say you have a door, a box, etc) and they each have their own script, but you want to tie them all into a public variable on your button script, your best bet is to implement an interface. Then you set the public variable to be of the interface. Then each script that implements the interface must have the method in it.
So, basic example
public Class Door : IActivate
{
public void Activate()
{
//door activate code
}
}
public Class Box : IActivate
{
public void Activate()
{
//box activate code
}
}
public interface IActivate
{
void Activate();
}
public IActivate target;
void Button()
{
target.Activate();
}
This is just an example and might not be perfect, but the main thing is you would implement the interface so that you know each other script will have a method you can call from the interface without caring what else the script does.
Thanks for Your input, I’ll check this
EDIT:
Ok, I got this working but with a little hack
I think as interface cannot be monoBehavour
public IActivate target;
doesn’t show in the inspector, so instead I used
public GameObject target;
and
target.GetComponent<IActivate>().Activate();
My full code:
Interface
public interface IActivate
{
void Activate();
}
Button
using UnityEngine;
public class DeleteMeIngameButton : MonoBehaviour
{
public GameObject target;
void Button()
{
if (target.GetComponent<IActivate>() != null)
{
target.GetComponent<IActivate>().Activate();
}
}
}
Box
using UnityEngine;
public class Box: MonoBehaviour, IActivate
{
public void Activate()
{
//do Box stuff
}
}
I’m still fuzzy, correct me if I’m wrong/can be better