- Home /
Question by
ceilingcat1234 · Sep 27, 2020 at 12:37 PM ·
instantiatederived-class
Instantiate method cause conversioning derived class to be base class on component variable.
Dear Community, I apologize in advance for my poor English. Instantiate method cause conversioning derived class to be base class on component variable. Please tell me how to not conversioning derived class to be base class, or alternative proposal. Thanks in advance for any answers.
Main.cs
using UnityEngine;
public class Main : MonoBehaviour
{
public Object obj;
void Start()
{
obj.objClass = new SubClass();
obj.Act();
Object dObj = Instantiate( obj ).transform.GetComponent<Object>();
dObj.Act();
}
}
[System.Serializable]
public class BaseClass {
public virtual void Action() {
Debug.Log( "BaseClass" );
}
}
[System.Serializable]
public class SubClass : BaseClass {
public override void Action() {
Debug.Log( "SubClass" );
}
}
Object.cs
using UnityEngine;
public class Object : MonoBehaviour {
public BaseClass objClass;
public void Act() {
objClass.Action();
}
}
Message
SubClass Main:Start() (at Assets/DupricateTest/Main.cs:12)
BaseClass Main:Start() (at Assets/DupricateTest/Main.cs:15)
Expect Message
SubClass Main:Start() (at Assets/DupricateTest/Main.cs:12)
SubClass Main:Start() (at Assets/DupricateTest/Main.cs:15)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613012641im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Checking if object intersects? 1 Answer
Fireball instantiate - lags 1 Answer
Referencing gameObject from script after Instantiate 0 Answers
Painting with collision box 0 Answers
GUIText Instantiation and Update the Instantiated Text. C# 1 Answer