Script only for cameras (or specific object type to set this context type).

Hi, is there a way to set “this” context type in a script? I’m sure this is possible. I can’t remember, but I saw that somewhere. … Restrict a script only for a specific game object type. For example only for “Camera”. So that “this” type is a camera and I could use “this.ScreenToViewportPoint”.

My current workaround is a public property to set this object. Or use “Camera.main”. But I wan’t the more elegant way to set this type.

GameObjects don’t have types in Unity. GameObjects have components. There is no such thing as a “camera gameobject”. There are only GameObjects that have Camera components attached to them.

You can use the RequireComponent attribute to ensure that your script can only be added to GameObjects that have a specific component type attached to them. This will also automatically add that component type to the object when you add your script to the object. Unity - Scripting API: RequireComponent

Example:

[RequireComponent(typeof(Camera))]
public class MyCameraScript {
  private Camera cam;

  void Awake() {
    // We can be certain this component exists because of the attribute
    cam = GetComponent<Camera>();
  }
}
1 Like

Thanks. I remember. That’s exactly what I wanted.