简体   繁体   English

通过编程将相机对准unity3d中的对象

[英]Center camera on object in unity3d by programatically

i wanted to center my camera on object once they are turn is active.. But, i am unable to do it. 我想将相机旋转后将其对准物体。.但是,我无法做到这一点。

Here is my code: 这是我的代码:

public GameObject UserPlayerPrefab;
public Vector3 v3;

void Update()
    {
        transform.LookAt(UserPlayerPrefab);
    }

i already tried that, but it gave me the error, said that i have to use Vector3. 我已经尝试过了,但是它给了我错误,说我必须使用Vector3。 When i change the code to this one: 当我将代码更改为此:

void Update()
        {
            transform.LookAt(v3);
        }

it works, but not the camera is not center on the object however it is center on the Tile (which is the Plane). 它可以工作,但不是摄影机不在对象上居中,而是在图块(即平面)上居中。

How do i fix it? 我如何解决它? Thanks 谢谢

You shouldn't be trying to look at a prefab, but at an actual instance of the prefab. 您不应尝试查看预制件,而应查看预制件的实际实例。 But, putting that aside, what you're looking for is this: 但是,撇开这些,您正在寻找的是:

transform.LookAt(UserPlayerPrefab.transform.position);

Now, I would rather see something like this: 现在,我宁愿看到这样的东西:

public GameObject UserPlayerPrefab;
private GameObject userPlayerInstance;


// Somewhere, not necessarily Start(), you instantiate the instance of the prefab
void Start()
{
    userPlayerInstance = (GameObject)Instantiate(UserPlayerPrefab);
}

void Update()
{
    transform.LookAt(userPlayerInstance.transform.position);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM