Ссылка на класс Unity c#
Необходимо создать список, содержащий в себе ссылки на классы, чтобы в дальнейшем выбирать из них случайный и создавать его экземпляр. Во время создания такого списка вылетает исключение.
error CS0119: 'A' is a type, which is not valid in the given context
на строке с кодом
List<parent> list_classes = new List<parent>() {A, B, C};
Вот версия этого кода на языке Python:
import random
class parent:
def printt(self):
print(self.value)
class A(parent):
def __init__(self):
self.value = 'A'
class B(parent):
def __init__(self):
self.value = 'B'
class C(parent):
def __init__(self):
self.value = 'C'
list_classes = [A, B, C]
random_class = random.choice(list_classes)
random_class().printt()
Вот версия того же кода на языке c#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class parent {
public char value = 'P';
public void printt() { Debug.Log(this.value); }
}
public class A : parent {
public char value = 'A';
}
public class B : parent {
public char value = 'B';
}
public class C : parent {
public char value = 'C';
}
public class test: MonoBehaviour
{
void Start()
{
List<parent> list_classes = new List<parent>() {A, B, C}; // error CS0119: 'A' is a type, which is not valid in the given context
parent random_class = list_classes[Random.Range(0, list_classes.Count)];
new random_class().printt();
}
}
Прошу помочь решить данную проблему.
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
Немного не так наследование делается, и в списке наверное нужны типы.
public class Parent {
protected char value = 'P';
public void Print() {
Debug.Log(value);
}
}
public class A : Parent {
public A() {
value = 'A';
}
}
public class B : Parent {
public B() {
value = 'B';
}
}
public class C : Parent {
public C() {
value = 'C';
}
}
public class Test : MonoBehaviour
{
void Start()
{
List<Type> list = new List<Type>() { typeof(A), typeof(B), typeof(C) };
Type randomType = list[Random.Range(0, list.Count)];
Parent randomItem = (Parent)Activator.CreateInstance(randomType);
randomItem.Print();
}
}