- Home /
How do I check if a derived class is a certain class?
For example,
I have ScriptableObject A and then 3derived class A1 A2 A3
There is also Runtime Class B and derived from it, B1 and B2
B1 can only use A1 and A3 B2 can only use A2
And finally, there is manager Class C
Class C can only call function from base class B, But the said function can received any version of classA
As such, class B1 and B2 have a need to check which kind of A they are receiving.
public class B1 { void Update() { if( A is not A1 or A2 ) return; }
}
Did my answer resolve your issue? If not, can you explain what is the error/what is missing? If yes mark it as accepted answer.
Answer by CodeElemental · Feb 20, 2014 at 04:05 PM
if (objA is ClassA)
More here
In your specific scenario :
public class B1 {
void Update()
{
if(!(A is A1 || A is A2))
return;
}
}
Helped a lot! Is there also a way to then call a method which only exists on A2 for example?
Of course there is a way ^^. If you use an older version of Unity you would either use an "as" cast in combination with a null check or an "is" check followed by a normal cast. However in newer Unity versions where C#7+ featues are supported you can use an is operator with integrated variable declaration- So you can do this:
if (myVar is $$anonymous$$yType obj)
{
// use the variable "obj" here
}
edit
Just for completeness, here are the other two cases I mentioned above
// is operator in combination with normal cast.
if (myVar is $$anonymous$$yType)
{
$$anonymous$$yType obj = ($$anonymous$$yType)myVar;
// use the variable "obj" here
}
// as operator with null check
$$anonymous$$yType obj = myVar as $$anonymous$$yType;
if (obj != null)
{
// use the variable "obj" here
}
The "as" cast is slightly more expensive than a normal cast but usually cheaper than an "is" check and a normal cast combined. The as cast will not generate any error or exception if the cast fails but simply returns null if the cast is not possible. The normal cast will throw an invalid cast excpetion if the cast is not valid.
The new "is" operator is now the shortest and cleanest solution in most cases. The "as" cast variant is useful if your source variable could also be null as this would be checked implicitly with the null check.
Your answer
Follow this Question
Related Questions
[CLOSED] How do I check if a derived class is a certain class? 0 Answers
C# finding gameobject that created this class, and do I need to clear them? 1 Answer
How do I check if a derived class is a certain class? 0 Answers
Convert SerializedProperty to Custom Class 7 Answers
How to declare multiple variables using a for loop in class declaration? 0 Answers