1.访问自身物体上的其他组件(组件又称为js脚本)
GetComponent: 你可以使用GetComponent找到任何附加到同一个物体上的任何脚本或者组件,如果找到了同一物体上的其他脚本就可以条用其他脚本的方法,或设置他们的参数
如:function Update ()
{
//找到物体上move脚本的Dosomething()方法
GetComponent(move).Dosomething();
}
//move脚本内有以下内容
function Dosomething()
{
//找到物体上的Transform脚本的transform对象的Rotate GetComponent(Transform).transform.Rotate(Vector3(0,5,0)*Time.deltaTime);
}
执行的结果为:物体每秒钟绕y轴旋转5度
2.访问其他物体上的脚本(通过监视面板赋值)
假设场景中有物体cub1,cub1上的脚本otherscript为:
var foo=5;
function Dosomething()
{
transform.Rotate(0,foo,0);
}
物体cub2上有脚本testscript为:
var target:Transform;
function Update () {
//找到物体cub1上的otherscript脚本,并执行他的方法Dosomething();
target.GetComponent(otherscript).Dosomething();
}
将cub1拖到cub2上面的target上,则执行结果为:物体每秒钟绕y轴旋转5度
还可以这样:
假设场景中有物体cub1,cub1上的脚本otherscript为:
var foo=5;
function Dosomething()
{
transform.Rotate(0,foo,0);
}
物体cub2上有脚本testscript为:
var target: otherscript;
function Update () {
//找到物体cub1上的otherscript脚本,并执行他的方法Dosomething();
target.Dosomething();
}
将cub1拖到cub2上面的target上,则执行结果为:物体每秒钟绕y轴旋转5度
3.访问其他物体上的脚本(通过物体层次定位)
父子物体关系:如果将一个物体拖到另一个物体则这两个物体就有了父子关系
假设场景中有物体cube,cube1的脚本cub1为:
function Update () {
//找到物体cube3并调用他的cub2脚本的Dosomething();方法
transform.Find("Cube3").GetComponent(cub2).Dosomething();
//找到物体cube2并设置它绕y轴每帧旋转2度
transform.Find("Cube2").Rotate(0,2,0);
//循环每个子物体设置他们绕y轴旋转1度
for(var child:Transform in transform)
{
//child.Transform(0,1,0);
child.Rotate(0,1,0);
}
}
物体cube2上有脚本cub2为:
var foo=5;
function Dosomething{
transform.Rotate(0,foo,0);
}
物体cube3上有脚本cub2为:
var foo=5;
function Dosomething{
transform.Rotate(0,foo,0);
}
4.访问其他物体上的脚本(通过tag 定位)
function Update () {
//找到标签为cube11的物体 设置它每帧绕y轴旋转3度
GameObject.FindWithTag("cube11").transform.Rotate(0,3,0);
//找到cube11物体调用他的Dosomething();方法
GameObject.FindWithTag("cube11").GetComponent(cub2).Dosomething();
}
5.访问其他物体上的脚本(通过FindObjectsOfType定位所有具有同类脚本名称的物体)
我们可以通过FindObjectsOfType定位所有具有同类脚本名称的物体或者通过FindObjectOfType找到这个类型的第一个物体
function Update () {
//找到脚本为cub2的物体并执行他的.Dosomething();方法
var other:cub2=FindObjectOfType(cub2);
other.Dosomething();
//找到所有拥有cub2脚本的物体并执行他们的Dosomething()方法
for(var a :cub2 in FindObjectsOfType(cub2))
{
a.Dosomething();
}
}
本文来源:https://www.2haoxitong.net/k/doc/b230686a58fafab069dc0237.html
文档为doc格式