I have a method that among other things stores info what kind of debuff was used like this:
public void AddDebuff(Debuff debuff)
{
whatKinfOfDebufftIsIt = debuff;
}
Debuff class is parent class for classes like DamageDecrease and DefenseDecrease example code:
public class Debuff: MonoBehaviour
{
//code
public class DamageDecrease : Debuff
{
//code
}
public class DefenseDecrease : Debuff
{
//code
}
}
And for now I pass this parameter like this:
AddEffect(new Debuff.DamageDecrease());
But unity throws this warning:
You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed.
MonoBehaviours can only be added using
AddComponent(). Alternatively, your
script can inherit from
ScriptableObject or no base class at
all
What I’m doing is working but this warning is a bit frustraiting.
Is there a better way of passing parameter like that? (by better I mean without new keyword to not get warning)
The warning you’re encountering is because you’re trying to create an instance of a MonoBehaviour-derived class using the new keyword. MonoBehaviour classes can only be created by adding them as a component to a GameObject.
A better approach to this situation is to use a base class that doesn’t inherit from MonoBehaviour. You can convert your Debuff class to inherit from ScriptableObject or not inherit from any base class at all. Here’s an example of how you could change your code:
public class Debuff
{
// code
public class DamageDecrease : Debuff
{
// code
}
public class DefenseDecrease : Debuff
{
// code
}
}
With this change, you can continue using the new keyword without receiving the warning:
AddEffect(new Debuff.DamageDecrease());
However, if you need MonoBehaviour functionality in your Debuff classes, you should create a new GameObject and add the Debuff component to it. Here’s an example of how you could do that:
public void AddEffect<T>() where T : Debuff
{
GameObject debuffObject = new GameObject("Debuff");
T debuff = debuffObject.AddComponent<T>();
whatKinfOfDebufftIsIt = debuff;
}
Then you can call the method like this:
AddEffect<Debuff.DamageDecrease>();
This way, you’re adding the Debuff component to a new GameObject without using the new keyword. Choose the approach that best fits your needs.