Hi, I’m new to Unity, and I couldn’t find anything pinpointing my issue anywhere.
I have an enemy I need to duplicate, so I made a prefab for it, but the prefab doesn’t have the completed fields the original has for its targeting component. I need the enemy to target the player, but for some reason the enemy’s script that had a public variable for the player’s transform was empty. Thus, I made my player a prefab, so I could drag it into the empty variable. Now nothing works. Why? It doesn’t make sense because the prefab’s instantiated clones should have the correct player to chase, yet they just sit there and do nothing.
I have the original GameObject on the hierarchy, and the clone of the prefab of it, they are identical, yet the original GameObject targets the player, whilst the clone doesn’t.
If I don’t make anything a prefab, everything works flawlessly. Am I missing a key detail?
I don’t know what could help, but here’s some stuff:
1. Code for instantiating prefab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gameplay : MonoBehaviour
{
// original prefab
public GameObject originalRook; // yes it is a chess themed game
void Start()
{
spawnRook(3, 1);
}
// params = x coord and y coord to spawn rook
void spawnRook(float x, float y) {
Vector3 spawnLocation = new Vector3(originalRook.transform.position.x + x, originalRook.transform.position.y + y, 0);
GameObject rook = Instantiate(originalRook, originalRook.transform);
rook.transform.position = spawnLocation;
}
}
How would I do that? I get an error, “instantiate objects with a parent which is persistent. New object will be created without a parent.” which I don’t understand, since the object I’m trying to instantiate is the parent. Isn’t it impossible to make a child a prefab?
Right now your rooks have a reference to the player prefab, and this prefab is not the same object that you have in your scene, that is an instance of the prefab.
You want to get that instance of player and set that as your instantiated rook’s target.
So in simple steps:
Have a reference to the player instance (this can be done through serialised/public fields in the inspector)
Instantiate the Rook
Set the Rook’s target as the referenced instance of the player
This should be a good lesson in the difference between scene level objects, and asset level objects.