Camera wont follow Prefab?

Updated on April 19, 2018 in [A] Tutorials
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on April 19, 2018

Hello everyone! I used the tutorial Smooth Camera Follow in Unity – Tutorial. My question is when I made my GameObject a Prefab and Itempooled using SetActive() My camera broke and now focuses on the world coordinates. What can I do to have the camera follow the GameObject again? Much thanks 🙂

 

 

 


 
 
 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CameraFollow : MonoBehaviour {
 
public Transform target;
 
public float smoothSpeed = 0.125f;
public Vector3 offset;
 
public GameObject scopeOverlay;
 
public GameObject Camera;
 
private Vector3 initialPosition;
private Quaternion initialRotation;
 
private void Start ()
{
// Save initial transform values
initialPosition = transform.position;
initialRotation = transform.rotation;
}
 
void FixedUpdate ()
{
if (Input.GetKeyDown("d"))
{
Camera.SetActive(false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
 
transform.LookAt(target);
 
}
 
if (Input.GetKeyDown("e"))
{
// Restore transform values
transform.position = initialPosition;
transform.rotation = initialRotation;
 
Camera.SetActive(true);
scopeOverlay.SetActive(false); //To disable it
}
}
}
 
 
 
 
 
 
 
 
 
 
 
 

  • Liked by
Reply
0 on April 19, 2018

You can’t set a reference like this to prefabs. All of this code relies on Camera and target always being set to something active in the scene right now.

You either need to set them to references in the inspector to GameObjects in the scene right now, or you need to set them in an some other function that lets you grab them at run-time, and not let the update loop run while any of them are null.

  • Liked by
Reply
Cancel