Unity 3d C#脚本(1)
2016-12-30 09:51
337 查看
创建和使用脚本
创建C#脚本Assets > Create > C# Script初始内容
using UnityEngine; using System.Collections; public class MainPlayer : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
要使脚本运行,需要将脚本附加到游戏对象(GameObject)上。可以通过将脚本拖拽到hierarchy视图的特定对象上进行绑定,之后在Inspector视图上会出现新添加的脚本的组件。
测试:
在Start中 添加代码
// Use this for initialization void Start () { // Debug.Log is a simple command that just prints a message to Unity’s console output Debug.Log("I am alive!"); }
点击运行,会在 console窗口中看到打印信息。
变量和Inspector
在脚本中可以设置变量,使可编辑变量出现在inspector视图中。将变量设置为public才能在Inspector视图中显示可编辑变量。using UnityEngine; using System.Collections; public class MainPlayer : MonoBehaviour { public string myName; // Use this for initialization void Start () { Debug.Log("I am alive and my name is " + myName); } // Update is called once per frame void Update () { } }
代码会在Inspector视图当前组件中创建一个名为”My Name”的可编辑域。
编辑”My Name”之后点击运行,会在console窗口中看到打印信息。
用Components控制GameObjects
用GetComponent函数获取组件对象void Start () { Rigidbody rb = GetComponent<Rigidbody>(); }
一旦获取了组件对象,就可以改变其变量。
void Start () { Rigidbody rb = GetComponent<Rigidbody>(); // Change the mass of the object's Rigidbody. rb.mass = 10f; }
访问其它GameObject
public class Enemy : MonoBehaviour { public GameObject player; void Start() { // Start the enemy ten units behind the player character. transform.position = player.transform.position - Vector3.forward * 10f; } }
用如上方式,可以通过从Hierarchy面板向 Inspector中拖拽目标的方式给变量赋值。
用GameObject.Find可以通过名字查找特定GameObject
GameObject player; void Start() { player = GameObject.Find("MainHeroCharacter"); }
还可以通过GameObject.FindWithTag、FindGameObjectsWithTag获取特定tag的一个或一组GameObject。
GameObject player; GameObject[] enemies; void Start() { player = GameObject.FindWithTag("Player"); enemies = GameObject.FindGameObjectsWithTag("Enemy"); }
相关文章推荐
- Unity 3d C#和Javascript脚本互相调用 解决方案(非原创、整理资料,并经过实践得来)
- Unity 3D视频播放器场景C#脚本
- Unity 3D功能主界面C#脚本
- Unity 3D Coroutine&yield(C#脚本)
- Unity 3D开发-C#脚本语言的一些基础用法
- unity 3D登录界面C#脚本
- Unity 3d中导入c#脚本时出现 can't add script 如何解决
- unity 3D学习日记:创建一个小场景并编写简单C#移动脚本
- Unity 3D 动态创建对象,并渲染贴图,动态添加删除脚本
- unity中js脚本与c#脚本互相调用
- Unity 3d 保存玩家数据到本地之PlayerPrefs, C#封装
- 【Unity 3D】学习笔记二十一:unity游戏脚本(一)
- Unity 3D 监听键盘 返回键退出程序C#
- 【Unity 3D】学习笔记二十五:unity游戏脚本(五)
- Unity--在C#脚本中调用JS脚本函数并传参
- Unity3d不支持vistual studio2012?用vs2012打开unity c#脚本进行编码的方法。
- 【Unity 3D】学习笔记二十三:unity游戏脚本(三)
- < Unity 3D专栏 >动态创建对象,并渲染贴图,动态添加删除脚本
- Unity3.5的脚本编写(C#),请使用VS编写,然后用MonoDevelop调试!
- unity 3D学习备忘二(unity 3D的脚本调试)