- Home /
Script to create instance from in inspector
I have a class, SplineController, which I want to allow to have different types of splines to be used for different purposes (as they have different properties). All my spline classes implement an interface, ISpline.
public class SplineController { public ISpline positionSpline;
public void Start()
{
// Obtain SplineControllerWaypoint objects and add points to the ISpline
SplineAnimationControllerWaypoint[] waypoints =
transform.parent.GetComponentsInChildren<SplineAnimationControllerWaypoint>();
foreach (SplineAnimationControllerWaypoint waypoint in waypoints)
{
positionSpline.AddPoint(waypoint.position);
}
positionSpline.Build();
}
}
Now I would like to specify which script to use to create the instance of ISpline from through the inspector. What is the way to select the script and create the ISpline instance from there?
Answer by Adam Rademacher · Oct 18, 2010 at 03:01 PM
If you have an instance of "SplineController" in the game, it should have a field for your public ISpline. Drag and drop the ISpline you want to reference onto that game object like you would any other component reference.
If you want to do it dynamically (through scripting), you'll have to probably do GameObject.Find or .FindWithTag and GetComponent();
Answer by jorrit5477 · Oct 19, 2010 at 01:46 PM
In order for that to work ISpline can't be an interface (the ISpline property is not visible), but must at least inherit from UnityEngine.Object. If I do that, I am still not able to drag or select a script onto the property field (there is nothing to select).
I have managed to get it up and running: - Made ISpline and an abstract base class, which inherits from MonoBehaviour - Hide the spline property in the inspector - Users must add ISpline implementations to the same game object the spline controller is added to. - SplineController uses the first ISpline implementation found
You could avoid the abstract base class by iterating through all the components looking for one whose type implements the ISpline interface -- "if (component.GetType().GetInterface("ISpline") != null)"
Your answer
Follow this Question
Related Questions
How can i get SerializedProperty from UnityEvent which in List. Sorry for my Eng. 2 Answers
OnInspectorGUI changes reset when played in editor or building 2 Answers
How can I recreate the Array Inspector element for a custom Inspector GUI? 7 Answers
How to Hide/Show List or Array in the inspector based on a variable? 0 Answers
Create inspector drop-down button based on the content of a list in editor mode 1 Answer