- Home /
Why can't I attach my Player to a transform in my script?
I am trying to make a script where the zombie looks for the player and if the player enters the boundaries it will start chasing it. My problem is that I can't attach my player to the script in the inspector and I am unsure why. I don't have a problem with the code(at least I don't think so) only with it not attaching. The player is a prefab from the unity Standard assets. Edit: The script is attached to a prefab in my assets. The player in in the hierarchy.
Just in case here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ZK_attack : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 4.5f;
public float MaxDist = 4.0f;
public float MinDist = 1.5f;
private Coroutine animat = null;
private Animator anim;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
anim.SetBool("inRadius", true);
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
anim.SetBool("AttackingPlayer", true);
}
}
Code looks fine. Rather odd it wouldn't let you as anything with a Transform should be able to be dropped into Player
which is just about everything that isn't UI
. Just to be sure, you are dragging the object onto a script that is currently on another object correct? As opposed to trying to drop it into the script directly in Assets
.
The script is attached to a prefab in my assets. The player in in the hierarchy.
Answer by HellsHand · Apr 13, 2021 at 06:34 PM
Ok, the problem is that you can only drag objects into scripts that are in your scene already, unless they are prefabs themselves in the assests
folder, even though it is on an object. To accomplish what you need, in your Start()
add Player = GameObject.Find("...name of object you wish to set as Player").transform;
Your answer
Follow this Question
Related Questions
Customize how class attributes are shown in the Inspector? 0 Answers
Unity editor - sort items in any list visible in inspector 2 Answers
Serialize Custom Abstract Class (No-MonoBehaviour / No-ScriptableObject) 1 Answer
UnityEvent Inspector bug at Unity 2020.3 0 Answers
Make a custom inspector that shows a group of variables in form of list 2 Answers