Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c# - How to convert a string into a type?

Hi so I'm trying to convert a string named compToAdd into a type and im not sure how to do it, I tried googling for almost 5 hours now and here I am.

The goal would be to make slot.AddComponent<compToAddType>(); run properly

Here is a snippet of the code:

    public string foundationComp;
    public string turretComp;

    public void buildFoundation()
    {
        Build(foundationComp);
    }

    public void buildTurret()
    {
        Build(turretComp);
    }

    public void Build(string compToAdd)
    {      
        Type compToAddType = Type.GetType(compToAdd); //I thought this line would convert the string into a type
        slot.AddComponent<compToAddType>(); // but then I get an error here saying that compToAddType is a variable thats being used like a type..so how am I supposed to convert it?
//just note that 'slot' here have no problem and is a gameobject the problem is on the word 'compToAddType'
    }

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general see Type.AssemblyQualifiedName.

If you don't have that you will need to at least have a reference to the Assembly in question and then use Assembly.GetType.

You can also get the assembly if you know at least one type from the according assembly via Assembly.GetAssembly(theKnownType)


That said, you can not use the generic version GameObject.AddComponent<T>() since the type-parameter of generics need to be compile-time constant!

You can however simply use the non-generic version of GameObject.AddComponent(Type)

public void Build(string compToAdd)
{      
    Type compToAddType = Type.GetType(compToAdd); 
    slot.AddComponent(compToAddType); 
}

(Actually there even was an overload directly taking a string as parameter but it was deprecated.)


Finally I personally would avoid it completely if possible! Instead of relying on your strings being correct, why not rather use e.g.

public void buildFoundation()
{
    slot.AddComponent<FoundationComponnet>();
}

public void buildTurret()
{
    slot.AddComponent<TurretComponent>();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...