- Home /
Instanced Prefabs won't face camera.
Hi,
I created a scene where a script attached to an empty GameObject, instances prefab's into the scene. See images. (test scene, objects will be replaced)


So far so good!. I want the objects in the scene to face the camera. These cubes will be replaced by - camera facing -billboards.
Here's the script that's attached to the empty GameObject:
var prefab : GameObject;
var gridX = 5; var gridY = 5; var gridZ = 5; var spacing = 2.0;
function Start () { for (var z = 0; z < gridZ; z++) { for (var y = 0; y < gridY; y++) { for (var x= 0; x < gridX; x++) { var pos = Vector3 (x, z, y) * spacing; Instantiate(prefab, pos, Quaternion.identity); } } } }
In the inspector I drag a prefab (cube) to it. So far so good. It creates the 3d cube grid.
I've tried several ways to have the instanced cubes oriented to the camera. The scripts work on non instanced - instanciate() - objects. Drag the prefad to the hierarchy, attach script and the object faces the cam.
The look at cam script:
var cameraToLookAt: Camera;
function Update() { var v: Vector3 = cameraToLookAt.transform.position - transform.position; v.x = v.z = 0.0; transform.LookAt(cameraToLookAt.transform.position - v); }
Q: How do I get the instanced cubes (or other prefabs) face the camera?
Thank you
Answer by Anton Petrov · Nov 24, 2010 at 08:28 PM
Usualy Update() does not work in edit time. And you should apply [ExecuteInEditMode] attribute to the Update method.
And your script looks bad. What is v.x = v.z = 0????
I can suggest you my billboard script:
public class Billboard : MonoBehaviour { public bool UniformSize = false; public float UniformSizeFactor = 0.1f;
void Update ()
{
transform.LookAt( Camera.current.transform, Camera.current.transform.up );
if ( UniformSize )
{
float scale = UniformSizeFactor * Vector3.Distance( Camera.current.transform.position, transform.position );
transform.localScale = new Vector3( scale, scale, scale );
}
}
}
Here UniformSize and UniformSizeFactor will allow you to create billboard which do not change their size when camera moves.
I added this line: using UnityEngine; or it wouldn't compile. After adding the script to the empty GameObject I get this error: NullReferenceException Billboard.Update () (at Assets/Billboard.cs:9) Something named wrong, or JS and C# can't work on the same object?
To add: the error appear when I run the scene, than it pauses and give the error.
Looks like Camera.current is null? Please make some checks.
Answer by Remy 1 · Nov 25, 2010 at 09:16 AM
Thank you Anton.
The scripts ain't mine. I'm not a coder. I will try to make the adjustments tonight.
I will let you know if it worked.
Your answer
Follow this Question
Related Questions
Camera Auto-Align with the nearest object with a determinated tag 0 Answers
Camera Auto-Align with the nearest object with a determinated tag 0 Answers
camera script problems 2 Answers
Toggle Control between multiple turrets 0 Answers
RPG scripts 2 Answers