演示代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//需要添加这个引用
using UnityEngine.Animations;
public class Test : MonoBehaviour
{
private void Start()
{
SetLookAtConstraint();
}
/// <summary>
/// 代码添加LookAtConstraint朝向的对象
/// </summary>
private void SetLookAtConstraint()
{
//首先确保存在该组件
if (GetComponent<LookAtConstraint>())
{
//LookAtConstraint的Add方法需要将ConstraintSource类型的对象填入
//可以先创建本对象,然后往ConstraintSource中添加位置和权重
ConstraintSource source = new ConstraintSource();
//添加位置
source.sourceTransform = Camera.main.transform;
//设置权重
source.weight = 1;
//将创建的ConstraintSource对象添加进入即可
GetComponent<LookAtConstraint>().AddSource(source);
}
}
}
运行前
运行后
此时方块已经朝向了摄像机。