prefabs break movement scripts,
,I'm doing the Create With Code tutorials and working on my prototype, and I got everything working well- enemies chasing player, player dying dramatically, lots of good stuff. BUT. When I make my enemies and player into prefabs, my enemy movement goes nuts. It's the same script that's on those chasing balls from the 4th week, basically, and it works fine until I change everything into prefabs. Any help would be appreciated- I'm stuck! Here's my enemy controller.
private float speed = 5.0f;
private Rigidbody enemyObjectRb;
public GameObject player;
void Start()
{
enemyObjectRb = GetComponent<Rigidbody>();
}
void Update()
{
enemyObjectRb.AddForce((player.transform.position-transform.position).normalized *speed);
}
I think it's something about how it references the player gameobject, because it works fine in the scene until I make them prefabs, then it loses the unity reference to the player in my enemyController script. I have to drag the player gameobject in to the scripts in the Unity inspector again. But then my movement goes nuts! The enemies fly all over the place and never hit the player. What the heck? Does anyone know? I'd sooo love an answer.
I found that making prefabs is useful for objects that don't have a lot of scripts on them. Pick ups, ragdolls rockets and other things I instantiate. When I tried to make a prefab out of an enemy, I found that the script suddenly didn't recognize objects that I had dragged into variable slots on his script. Like the player , for instance, or anything else that was not also a prefab. It became a slippery slope because when I then made the player a prefab so the enemy would interact, a lot of his scripts no longer recognized non prefabs. so items that get dragged into these prefab slots need to come from the prefab folder and not from your scene. Or you can change the scripts in prefabs to actually FIND things in the scene with GameObjectFind. So now I don't destroy dead enemies and respawn them from prefab, if they die I set then SetActive (false) and setActive ( true) when I want to respawn and move them to new spawn point
Your answer
Follow this Question
Related Questions
Bullet not moving rigidbody2d,AddForce not working for bullet 1 Answer
Can you configure prefabs in code? 0 Answers
Unity Addressable for player skins 0 Answers
prefab/instantiate problem. C#,Instanciate/Prefab problem. 0 Answers
How to account for RNG when multiple GameObjects are using the same script? 1 Answer