Unity学习日记-第二个Demo,脚本间的参数传递

在最初的Unity学习里面写到了一个Demo,功能是当鼠标悬停在一个cube时改变它的颜色。但该如何在不同的object 的脚本之间进行控制的问题一直卡住了我,今天把Unity的Manual仔细又看了看,终于初步的实现了功能,在上次的基础上重新设计了一个小Demo,功能是当鼠标悬停Cube上时,改变颜色,并使聚光灯指向它,脚本使用的是C#。(刚刚回顾了一下上次参考的blog,发现重要的知识点已经存在于里面代码中,只是作者没有强调出了,自己也就忽略了)


第一步,新建Project,搭建好基本的环境。把Direction Light强度调低一点,让Spotlight显现出来。剩下的工作就可以交给Scripts了。

Unity学习日记-第二个Demo,脚本间的参数传递_第1张图片


第二步,建立2个Scripts,一个LookAtCube,附在Spotlight 上,用于指引Spotlight 的方向,第二个是SwitchLight,附在方块上,让Spotlight指向它。


LookAtCube.cs 非常简单。Unity 的规则是大写字母开头的是函数或者结构体,小写字母开头的是变量,记住这一点再理解代码会轻松不少。

using UnityEngine;
using System.Collections;

public class LookAtCube : MonoBehaviour {

	public Transform target;//设置公开的变量,用于接收物件的transform信息。

	// Use this for initialization
	void Start () {
		target = GameObject.Find ("Main Camera").transform;
		//用GameObject.Find(name)得到物件,使Spotlight默认指向摄像机
	}
	
	// Update is called once per frame
	void Update () {
		transform.LookAt (target);
	}
}

SwitchLight.cs的注意点在于GetComponent 是无法直接访问其他Object的Component的,需要先用GameObject.Find() 访问到其他的Object 再使用。

using UnityEngine;
using System.Collections;

public class SwitchLight : MonoBehaviour {

	Transform newTarget;
	Color oriColor;

	// Use this for initialization
	void Start () {
		newTarget = transform;
		oriColor = GetComponent ().material.color;
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnMouseOver(){
		GameObject.Find ("Spotlight").GetComponent ().target = newTarget;
		//直接使用GetComponent()s是无法访问到target变量的,会返回null,
		//原因在于LookAtCube不是附在Cube上的Component,而是附在Spotlight上的,
		//GetComponent只能获得当前Object上的Component。
		GetComponent().material.color = new Color(1f,0f,0.5f);
		//这个语句因为是访问Object自己的组件,所以不需要使用Find查找。
	}

	void OnMouseExit(){
		GameObject.Find ("Spotlight").GetComponent ().target = GameObject.Find ("Main Camera").transform;
		GetComponent ().material.color = oriColor;
	}
}

两个脚本完成后,把LookAtCube 拖到Spotlight 上,SwitchLight 拖到5个Cube上,Demo就完成了。


效果:

Unity学习日记-第二个Demo,脚本间的参数传递_第2张图片

Unity学习日记-第二个Demo,脚本间的参数传递_第3张图片

Unity学习日记-第二个Demo,脚本间的参数传递_第4张图片

你可能感兴趣的:(学习笔记)