i’ve got a problem, i tried to search an answer in internet but i didn’t find it.
I’ve got this situation in my project:
public class GameController : MonoBehaviour {
public GameObject enemyShip;
public Object scriptToAdd; //custom script draggable in unity inspector
void Start()
{
enemyShip.AddComponent(); //How to do this?
}
}
Following different topics i found solutions like enemyShip.AddComponent(scriptToAdd.GetType()) but didn’t works ad this message was shown in console: “Can’t add component because ‘MonoScript’ is not derived from Component.”
Can you help me please? i’m a very beginner in Unity, sorry. I’m asking for help because i haven’t found nothing that can help me.
In this game Object I have a list of prefabs (EnemyShips) that instantiate a space ship in my project. I need to give them a beaviour for their movement and i’m trying to add a script (Behaviour) for each EnemyShips. Now i’m trying with one behaviour and if it’ll work will be an array.
The problem is that in my GameController.cs when i try to add the behaviour to a ship it doesn’t work, so actually i don’t know how to do
i tried to add the component in 2 differents ways, both didn’t work.
i need something like this:
var myEnemy = Instantiate(enemyShip, spawnPosition, spawnRotation);
myEnemy.AddComponent(); //this line is the problem
where “enemyShip” is one ship of the list and “Behaviour” is the object that i choose to add.
I tried to search an answer in this forum and in other places and the only solution that i found was something like this:
myEnemy.AddComponent(Behaviour.GetType());
however it gave me an alert in console with this message:
“Can’t add component because ‘MonoScript’ is not derived from Component.”
Use a ScriptableObject as a prefab asset and inside that have a field for the script you want to add, then point this class to tell the scriptableobject what to do (or just used it as a dumb data reference).
Is all you need. No need to cast, since AddComponent is a generic method. With generic methods you use the type, not the instance. So there is no point in defining the object in the field variable of your script.
Edit: and AddComponent is a method of GameObject. If you need to access the GameObject your custom script or component is attached to, use myComponent.gameObject. That’s a property of Component class.
I changed the structure of my project to adapt it at the normal use of the AddComponent method. I thought could be a good thing in my case and something possible to do so i asked you it that sure have a better knowledge than me. Thanks everyone for everything!