- Home /
How to set camera as Transform object
Hi lads, I'm new to unity. I have a game object to simulate the enemy and set main camera to Target:Transform. The enemy code is:
#pragma strict
var distance : float;
var Target : Transform ;
var detectRange : float = 25;
var attackRange : float = 5;
var movementSpeed : float = 5;
var damp : float = 4;
var bloodOut : GameObject;
function Start () {
}
function Update () {
distance = Vector3.Distance(Target.position, transform.position);
if(distance < detectRange && distance > attackRange){
renderer.material.color = Color.yellow;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Target.position - transform.position), Time.deltaTime * damp);
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if(distance > detectRange){
renderer.material.color = Color.green;
}
if(distance < attackRange){
renderer.material.color = Color.red;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Target.position - transform.position), Time.deltaTime * damp);
}
}
This works good. Then I made this enemy game object as a prefab and the code doesn't work. The Target is none and I can't drag camera in. Could someone tell me why and how to fix it?
But if I drag the prefab into map and drag camera into Target then it's working.
try adding this to Start()
Target = Camera.main.transform;
Not sure why that wouldn't work, do you have your main camera tagged as $$anonymous$$ainCamera? Try this
Target = GameObject.FindByTag("$$anonymous$$ainCamera")
yes yes, its working. thx man, I need to tag my camera as $$anonymous$$ainCamera!
Answer by robhuhn · Sep 03, 2013 at 06:48 AM
You can't assign objects to a script from the hierarchy view (where scene objects are listet) to the project view (where e.g. prefabs are listet). You would have to Instantiate an object using the prefab and assign the target at runtime.
enemy = Instantiate (prefab, Vector3(0, 0, 0), Quaternion.identity);
enemy.Target = myCamera; //or Camera.main.transform
Or what @getyour411 suggested was writing this at start of the enemy script:
function Start()
{
Target = Camera.main.transform;
...
}
yes, I forgot to tag my camera as $$anonymous$$ainCamera, now it's working, thx man!
Your answer
![](https://koobas.hobune.stream/wayback/20220613113451im_/https://answers.unity.com/themes/thub/images/avi.jpg)