New User, Making a Cube Follow Charactor

I want to make a cube follow me around. I thought it would make a good script however I need to "link it" to my position so I made a public transform. However this isn't showing up when I apply the script for me to drag an object onto...Any help would be much appreciated.

using UnityEngine; using System.Collections;

public class Follow : MonoBehaviour {

public Transform playerPos;
Vector3 chaseVel,chaseDir,chasPos;
// Use this for initialization

void Start () { chaseVel = (3,0,3); }

// Update is called once per frame
void Update () {
chaseDir = playerPos.position-this.position;
chaseDir= Vector3.Normalize(chaseDir)*chaseVel;
this.transform.position+= chaseDir;
}

}

To be completely correct here, instead of:

void Start () { chaseVel = (3,0,3); }

you should have something along the lines of:

void Start () { chaseVel = new Vector3(3f,0f,3f); }

However, multiplying two vectors together doesn't really make sense. To apply a non-uniform magnitude like that, you would need to multiply each component of the vector.

Thus, instead of multiplying two vectors together like this:

chaseDir = Vector3.Normalize(chaseDir) * chaseVel;

you want to do this:

Vector3 tmpNormalizedDir = Vector3.Normalize(chaseDir);
chaseDir = new Vector3(tmpNormalizedDir.x * chaseVel.x, tmpNormalizedDir.y * chaseVel.y, tmpNormalizedDir.z * chaseVel.z);

Also,

chaseDir = playerPos.position-this.position;

should probably be

chaseDir = playerPos.position-transform.position;

Finally, the whole script probably won't work well as it is because you're updating the position by a constant value once per frame. The Update() function gets called once per frame, so at lower framerates your object will lag and at higher rates it will get to the player faster.

So firstly, move this stuff from the Update() function to the LateUpdate() function -- this way, the player's position will be correct. And multiply your chaseDir by Time.deltaTime to ensure that the object always follows the player smoothly.

Your final code might look like this:

using UnityEngine;
using System.Collections;

public class Follow : MonoBehaviour
{
    public Transform playerPos;
    Vector3 chaseVel, chaseDir, chasPos;

    void Start() { chaseVel = new Vector3(3f, 0f, 3f); }

    void LateUpdate()
    {
        chaseDir = playerPos.position - transform.position;
        Vector3 tmpNormalizedDir = Vector3.Normalize(chaseDir);
        chaseDir = new Vector3(tmpNormalizedDir.x * chaseVel.x, tmpNormalizedDir.y * chaseVel.y, tmpNormalizedDir.z * chaseVel.z);
        chaseDir *= Time.deltaTime;
        this.transform.position += chaseDir;
    }
}

Why is it that you have to parse each vector? I thought that was how vector multiplication was handled. Also, this.position and transform.position are not the same? Thank you very much your full answer it is very helpful and insightful.

I did know about that fixed update though, thank you.