Search Unity

How would I find a specific gameobject for the camera to follow?

Discussion in 'Scripting' started by unfungmz, Aug 26, 2017.

  1. unfungmz

    unfungmz

    Joined:
    Jul 29, 2017
    Posts:
    162
    I'm coming from Director, so I'm trying to learn the workflow for Unity, and I'm wondering about how you would go about locating a specific gameobject for the camera to follow.

    I have several gameobjects using a custom built movement/physics script. I have public static variables set up for the X, Y, and Z of the gameobject. I can pull these variables into the camera's script in order to figure out where the camera should move to.

    float WhereToGoX = CharMoveScript.MyX;

    So I pass this into my camera script, but the issue is that it's going to pulled it from every CharMoveScript C# script that's running. I want to be able to differentiate between those scripts so I'm only pulling variables from one of them.

    Or maybe I'm just going about it the complete wrong way. That's possible, because again, I'm learning the Unity3D workflow from what I'm used to in Director. What would be the best way to have my camera script locate a specific object (by name?) to figure out where we're moving to?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,738
    The usual Unity pattern involves having a script that drives the camera, and then some attached parameters.

    The most common is the SmoothFollow style script (there's a million subtle variants out there) that takes a reference to a Transform it is following, and parameters for how far behind, how far above, etc.

    Generally you either set those properties up in the scene you are in, or if you do it in code, you use something that acquires a reference to the desired target Transform, and sets it into the camera object.

    How generic and future-proof you make it is up to you. I highly recommend just starting simple and seeing if it meets your needs. It might be all you need!

    For instance, here's a very basic yet highly-configurable SmoothFollow script:

    https://gist.github.com/Hamcha/6096905
     
  3. unfungmz

    unfungmz

    Joined:
    Jul 29, 2017
    Posts:
    162
    AHHH...see, I was doing it completely backwards. I should be sending data to the camera (from my character script) instead of having the camera querying information (since it's not sure which one to pull from).