i am trying to create a camera shake when a prefab comes near to the camera, so i need to drag the camera to the reference slot of the prefab in the inspector, now i know this cant seem to be done so is there a way to do this without having the use find gameobject in a script on every prefab as this will be highly cpu intense with lots of prefabs
i know i can access a script on the camera from the prefab using shared refs but i need to access the actual camera transform not a component on the gameobject
any help really appreciated as i am a bit stuck
The easiest solution in your case would probably be to use sphere colliders and OnTriggerEnter to detect when one of your prefab instances comes near the camera. Then you can just use the transform property to access the transform of the camera.
using UnityEngine;
[RequireComponent(typeof(Camera)), RequireComponent(typeof(SphereCollider))]
public class CameraShaker : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
ShakeCamera(transform);
}
private void ShakeCamera(Transform cameraTransform)
{
// shake the camera transform
}
}
If you don’t want to use colliders, then the way to avoid finding the camera again for each camera shake is to cache a reference to the camera in a static variable, and then reuse that same reference every time.
Here is one example how you could do it:
using UnityEngine;
public class CameraShaker : MonoBehaviour
{
private static Transform cameraTransform;
private void Awake()
{
// cache reference to this component during start up
cameraTransform = transform;
}
// Call CameraShaker.ShakeCamera() to shake the GameObject that contains this component
public static void ShakeCamera()
{
// add code to shake cameraTransform here
}
}
You can also use Camera.main to find the camera in your scene that has the “MainCamera” tag. But note that it also uses FindGameObjectsWithTag internally, so you should still cache the result into a static variable after the first time you call it, if you want to avoid that.
the above just gives this error:
Assets/ShakeableTransform.cs(84,9): error CS0120: An object reference is required to access non-static member
Post the code and I can take a look. Did you perhaps forget to make the transform field static?
nah, that is what was really wierd, i checked a few times and all the static’s were in place but it gave 2 red errors of can not acces non static,.
i have managed a workaround using shared refs that seems to be working ok at the moment, if it gives me a problem tomorrow when i continue coding i will post here and hopefully i will get more help, so thank you for your help so far,… i may need assistance again.
cheers