1. 组件与脚本的关系
-
组件可以看做是类,脚本就是控制这些组件的逻辑关系。
举例:transform就可以看作一个类,position、rotation、scale就如类的属性。
-
组件的启用与关闭:点击Inspector面板上相应的组件图标右侧的复选项,来进行切换。
-
unity中的任何游戏物体都可以看作是一个对象。
2. 获取游戏物体组件
- 在unity中所有继承MonoBehaviour的类是不可以实例化的,unity都会自动创建实例,并且调用被重载的方法。这是unity的规则,如果你继承了MonoBehaviour请使用unity的规则来进行实例化这个类,至于想通过c#的new去实例化MonoBehaviour的类是不被允许的。
- unity中定义组件是
public Transform trans
; - 获取游戏物体组件代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
public Transform trans;
// Start is called before the first frame update
void Start()
{
//this 指代当前游戏物体
trans = this.GetComponent<Transform>();//泛型
//gameobject也是当前游戏物体
//trans = gameObject.GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
//打印物体位置
//transform是一个变量
Debug.Log( trans.transform.position);
}
}