- Home /
Script inheiritence and finding a certain component
Hello, I have a class ClassB which inherits from ClassA, I'm trying to make a editor script that finds all ClassA components and removes them, and then add ClassB to them. The only problem is my script is using a .GetComponent() to see if it should remove a script and add ClassB but the GetComponent is also bringing back anything that has ClassB on it as well.
Here is the code I'm using for the editor script.
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
class FindClassA
{
[MenuItem("Custom/FindClassA")]
static void Execute()
{
foreach (GameObject go in Selection.GetFiltered(typeof(GameObject), SelectionMode.DeepAssets))
{
if (go.GetComponent<ClassA>() != null)
{
Editor.DestroyImmediate(go.GetComponent<ClassA>(), true);
go.AddComponent<ClassB>();
}
}
}
}
When it find a ClassA in the component it works but when it finds a ClassB it still gets in to the if and then adds a second ClassB to the game object :/
Thanks in advance, Hans
Answer by Bunny83 · Sep 25, 2011 at 03:00 PM
Of course it does. If ClassB is derived from ClassA it IS also a ClassA, that's the point of inheritance. I guess you want to know whether the object is a derived form of ClassA or an instance of the base class (ClassA) itself.
One way that came to my mind is this one (not tested):
foreach (GameObject go in Selection.GetFiltered(typeof(GameObject), SelectionMode.DeepAssets))
{
ClassA tmp = go.GetComponent<ClassA>();
if (tmp != null && tmp.GetType() == typeof(ClassA))
{
Editor.DestroyImmediate(tmp, true);
go.AddComponent<ClassB>();
}
}
Usually GetType() should return the true type of the instance. In the case of a ClassB instance the comparison should fail. If that doesn't work you can also test the component against ClassB and only perform your actions when it's not a ClassB.
if (tmp != null && !(tmp is ClassB))
However, this is not as versatile as the first way, since it just test against ClassB. The first way should work for any ClassA derived classes.
Thank you very much Bunny, that works great I really appreciate you taking the time to help. Hans
Your answer
Follow this Question
Related Questions
How do I break apart an object? 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Who owns NetworkViews placed in the editor? 1 Answer
OnTriggerEnter - destroy (this.gameobject) if it collides with anything 2 Answers
How can I preserve static object/data between editor and play? 2 Answers