- Home /
The question is answered, right answer was accepted
Problem when assigning a prefab
Hi! I have a enemy "dad" that instantiates other enemy "child" in a specific point, my problem is... i assign the "player" prefab to target variable in the enemy that is going to be instantiated, but this enemy prefab do target to the original position of the player prefab was create, (for example, target to "0,2.5,0"). I have another enemy that is not instantiated, is from the beginning in the scene and work fine, where is the problem? Thanks :)
Answer by tormentoarmagedoom · May 23, 2019 at 10:19 AM
Hello.
Can you post the code you are using?
You say " i assign the "player" prefab to target variable" but.. a prefab is not a real object in the scene, as it name says is pre-fabricated, is not real yet, is not instantiated in the scene. You need to assign as target to follow a real instantiated object in the scene (you can find it, assign via script, assign via inspector... som any ways, but a created object!)
As said, please postr your code to see what are you trying to do!
Bye!
void CheckDistance()
{
if (Vector3.Distance(target.position,
transform.position) <= chaseRadius
&& Vector3.Distance(target.position, transform.position) > attackRadius)
{
if (currentState == EnemyState.idle || currentState == EnemyState.walk
&& currentState != EnemyState.stagger)
{
Vector3 temp = Vector3.$$anonymous$$oveTowards(transform.position, target.position,
moveSpeed * Time.deltaTime);
print("APARECE");
anim.SetBool("move", true);
rb2d.$$anonymous$$ovePosition(temp);
ChangeState(EnemyState.walk);
}
}
}
using UnityEngine;
using System.Collections.Generic;
using PolyNav;
//example
[RequireComponent(typeof(PolyNavAgent))]
public class FollowTarget : $$anonymous$$onoBehaviour{
public Transform target;
private PolyNavAgent _agent;
private PolyNavAgent agent{
get {return _agent != null? _agent : _agent = GetComponent<PolyNavAgent>();}
}
void Update() {
if (target != null){
agent.SetDestination(target.position);
}
}
}
I imagine that there has to be some way of assigning the "player" that is in the scene, to the variable target, without dragging it, in the void start or awake or something like this.
Yes.
Best way is assing a tag to the player (for example "Player"). SElect the player, and in inspector top bar, choose a tag or create a newone adn assign it.
Then to find the player in the scene use this:
GameObject PlayerObject = GameObject.FindObjectWithTag("Player");
So now, PlayerObject variable is the Player in the scene.
Bye!
Follow this Question
Related Questions
spawn from pool only if pool has inactive gameobjects 3 Answers
How do I rotate a prefab and instantiate it to go forward of my player? 0 Answers
How to change Image on button click in a prefab that is instantiated 1 Answer
Multiplayer prefab player fall through floor on instantiate 0 Answers
Instantiating random prefabs when the player passes through a trigger 1 Answer