Access a component variable with just a type

Hello!

I have this function that adds a item effect to the player, the item effect is a class defined by A in this case:

public void CallItemEffect<A>()
{
    player.AddComponent(typeof(A));
}

Lets suppose that A class (or type) is as follows:

class itemeffect
{
    public int id = 0;
}

And then I can call the function with:

CallItemEffect<itemeffect>();

That function will add the new component to the player, my question is what if I want to acces the public int id variable within the itemeffect class?

Let’s suppose I want to change the CallItemEffect function as follows:

public void CallItemEffect<A>()
{
    //If I try this Visual Studio will display an error "The Component class does not have a definition for ´id´"
    player.AddComponent(typeof(A)).id = 90;
}

That will happen since although typeof(A) is type of ‘itemeffect’, is being handled like if were type of ‘Component’ instead.

What would be the correct code to access the id variable? (It needs to be accesed within the CallItemEffect function)

Thanks so much!

Ah… for this, you need to put a constraint on your generic method. This is done like so:

public void CallItemEffect<A>() where A : itemeffect
{
    // code here
}

You are basically telling the generic method that it could only accept types of type itemeffect and its inheritors (is that what they’re called?).

However, you have to change the body to this instead:

public void CallItemEffect<A>() where A : itemeffect
{
    player.AddComponent<A>();
}

Now you can do player.AddComponent<A>().id and it should access itemeffect’s id variable.

Hope this helps!