Multiple PowerUps (One ItemBox)
Hi everybody!,
I have the abstract class PowerUp (That inherits from MonoBehaviour because I want to add the component to a gameObject):
 public abstract class PowerUp : MonoBehaviour
 {
     abstract public void Activate(GameObject go);
     abstract public void Desactivate(GameObject go);
 }
Then I have 2 diferent clasess that are PowerUp:
 public class Lightning : PowerUp
 {
     public override void Activate(GameObject go)
     {
         go.AddComponent<Lightning>();
         Debug.Log("You got Lightning!");
     }
 
     public override void Desactivate(GameObject go)
     {
         Debug.Log("Lightning is gone.");
         Destroy(go.GetComponent<Lightning>());
     }
     
 
     private void Update()
     {
         if (Input.GetButtonDown("Jump"))
         {
             Debug.Log("Hey!, I'm Jumping with Lightning!");
         }
     }
 }
 public class Fire : PowerUp
 {
     public override void Activate(GameObject go)
     {
         go.AddComponent<Fire>();
         go.transform.localScale *= 1.2f;
         Debug.Log("You got Fire!");
     }
 
     public override void Desactivate(GameObject go)
     {
         go.transform.localScale /= 1.2f;
         Debug.Log("Fire is gone.");
         Destroy(go.GetComponent<Fire>());
     }
 
     private void Update()
     {
         if (Input.GetButtonDown("Jump"))
         {
             Debug.Log("Hey!, I'm Jumping with Fire!");
         }
     }
 
 }
My problem becomes when I created a ItemBox that when hits the player, it adds a powerup to the player's gameobject.
this code works buts it appears that it is not the way todo it:
  public PowerUp GetRandomObject()
     {
         PowerUp[] objetos = { new Fire(), new Lightning()};
 
         int objectToReturn = Random.Range(0, 2);
 
         return objetos[objectToReturn];
     }
Unity tells me this:
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 UnityEngine.MonoBehaviour:.ctor()
My question is: How can I return a random type of the abstract PowerUp on the GetRandomObject method?
PD: "ItemBox" is like a lootbox, the idea is to pickup a random powerup from any ItemBox.
Your answer
 
 
             Follow this Question
Related Questions
AddComponent fails when passing in type, works when passing in name 0 Answers
Using StartCoroutine in a Nested Class 0 Answers
Why isn't my script inheriting from MonoBehaviour 0 Answers
My Monobehaviour Script doesn't get detected 0 Answers
Can not access an abstract class from another script! 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                