- Home /
Create a variable of type C# script?
Hi everyone!
In the game i'm making I have interactable objects (let's say for now Doors and Chests).
I have a script that will find the nearest GameObject with the "interact" tag, and if it's within a certain range it will search for the "proximity" script in the object and call a function.
And whenever i press "E" (if in range) it will call the "activate" function on the "proximity" script. This in turn should call the "objectInteract" function on a script i have in the gameObject. This script would change depending on the type of object it was (So Doors have the "door" script added through unity's interface and Chests have the "chest" script added the same way.
My problem is that i can't seem to find a way of having a public variable that will accept any kind of script for me to add through unity's interface.
I know i can have say public ScriptName script
, but i wanted a way to have public AnyScript script
Any idea if this is possible?
What about $$anonymous$$onoBehaviour
? You also have $$anonymous$$onoScript
, which references to the actual asset (script text)
Answer by tanoshimi · Jan 04, 2014 at 10:48 PM
No.
However, the problem you're describing can be solved using the OOP principle of polymorphism.
If you let "door" and "chest" both be derived from a common base class (call it "InteractiveObject", say), and define objectInteract as a virtual method in the base class, that method can be overridden to act in different, specific ways in each derived class.
So have one base class attached to all interactive objects like this:
public class InteractiveObject
{
// Virtual method
public virtual void objectInteract()
{
// Generic interactive stuff
}
}
Then also attach a more specific derived class for each type of object such as:
public class Door : InteractiveObject
{
public override void objectInteract()
{
// Specific Interaction code for doors...
// If also want to call generic stuff then add
base.objectInteract();
}
}
or:
public class Chest : InteractiveObject
{
public override void objectInteract()
{
// Specific Interaction code for chests...
// If also want to call generic stuff then add
base.objectInteract();
}
}
You can now call the method from the base class script using GetComponent(<InteractiveObject>).objectInteract() on any object and it will actually execute the more specific derived class function depending on whether the object has the Door or Chest script attached.
That's exactly what i needed!
I had thought about using a derived class (actually thought about using inheritance) but i wasn't really sure how to implement it, or even if it would work!
Thanks a lot!
Your answer
Follow this Question
Related Questions
Change a Variable with another script not working (C#) 4 Answers
One script, different variable for each object. 1 Answer
Multiple Cars not working 1 Answer
C# Make array based on script variable 1 Answer
How to call Variable across scripts. 2 Answers