- Home /
The question is answered, right answer was accepted
Bug: cannot assign public Transform variable. Unity 2D 5.2
HI,
I have a script that destroys a bullet when it collides with something. but i want it to reduce the health of my player. so I declared
public Transform player;
i come back to the inspector and try to assign the variable but it Does Not Assign. the problem is that it will not let me choose from my list of people in the Hierarchy! What must I do??
Here is my code:
using UnityEngine; using System.Collections;
public class EnemyShotDestroy : MonoBehaviour { public Transform player;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
Destroy(gameObject);
player.GetComponent<mover>().health -= 1;
}
if (collision.gameObject.tag == "Boundary")
{
Destroy(gameObject);
}
if (collision.gameObject.tag == "Bullet")
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
}
I attached this into the prefab of my EnemyBullet in Assets and when i try to assign the var. it doesn't work. When i bring it out into the World it does let me assign but its clones dont work... Heres by EnemyBehavior Script:
using UnityEngine; using System.Collections;
public class groundEnemyBehavior : MonoBehaviour {
public float moveSpeed;
private float move = 1;
public float nextFire;
public float fireSpeed;
public Transform BulletSpawn;
public float fireRate;
public GameObject shot;
private GameObject cloneShot;
void Start ()
{
}
void FixedUpdate ()
{
if (move == 1)
{
GetComponent<Rigidbody>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody>().velocity.y);
}
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
cloneShot = (GameObject)Instantiate(shot, BulletSpawn.position, BulletSpawn.rotation);
cloneShot.GetComponent<Rigidbody>().velocity = new Vector3(-fireSpeed, 0);
}
}
}
Thanks for all who help I am really annoyed at this.
Answer by Tyche10 · May 12, 2016 at 05:11 PM
You cannot drag a gameobject from your scene hierarchy into a script attached to a prefab because the gameobject is part of the scene and is not always present like assets or resources are. You will need to look for it during runtime with a function like GameObject.FindObjectWithTag() or something similar.