在 C# 脚本中控制 游戏物体 GameObject 运动 , 要先获取该物体 , 然后 修改其 Transform 组件的属性 ;
在 游戏开始运行后 , 会自动执行 游戏物体 GameObject 上的 C# 组件代码 , 程序入口是 MonoBehaviour#Start() 函数 ;
在 C# 脚本中 , 主要的内容都在 Start() 函数 中实现 ;
using System.Collections.Generic;
using UnityEngine;
public class BehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("Unity 脚本入口 , 启动加载时调用");
}
// Update is called once per frame
void Update()
{
}
}
在 C# 脚本中 , 游戏物体类型是 GameObject , 可以通过调用 this.gameObject
获取当前 C# 脚本附着的物体 , 代码如下 :
// 获取当前组件附着的 游戏物体 GameObject
GameObject gameObject = this.gameObject;
获取 游戏物体 GameObject 的名称 , 调用 GameObject 类的 name 属性 , 即可获取当前物体的名称 ;
// 获取当前组件附着的 游戏物体 GameObject 名称
string name = gameObject.name;
完整代码如下 :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 打印日志
Debug.Log("Unity 脚本入口 , 启动加载时调用");
// 获取当前组件附着的 游戏物体 GameObject
GameObject gameObject = this.gameObject;
// 获取当前组件附着的 游戏物体 GameObject 名称
string name = gameObject.name;
Debug.Log("C# 脚本附着游戏物体的名称 : " + name);
}
// Update is called once per frame
void Update()
{
}
}
回到 Unity 编辑器 , 会自动编译 修改后的 C# 脚本 ;
该 C# 脚本 已经被附着到了 立方体上 , 在 Unity 编辑器 工具栏 中 , 点击 运行按钮 , 即可执行该 C# 脚本 ;
获取 游戏物体 GameObject 的 Transform 组件 , 调用 GameObject 对象的 transform 属性 即可 ;
// 获取当前组件附着的 游戏物体 GameObject 的 Transform 组件
Transform transform = gameObject.transform;
打印 Transform 组件的 位置 , 旋转量 , 缩放倍数 属性 :
// 获取 Transform 组件的 位置 , 旋转量 , 缩放倍数
Debug.Log("C# 脚本附着游戏物体的 Transform 组件数据 位置 : " + transform.position
+ " , 旋转量 : " + transform.rotation + " , 缩放倍数 : " + transform.localScale);
完整代码如下 :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 打印日志
Debug.Log("Unity 脚本入口 , 启动加载时调用");
// 获取当前组件附着的 游戏物体 GameObject
GameObject gameObject = this.gameObject;
// 获取当前组件附着的 游戏物体 GameObject 名称
string name = gameObject.name;
Debug.Log("C# 脚本附着游戏物体的名称 : " + name);
// 获取当前组件附着的 游戏物体 GameObject 的 Transform 组件
Transform transform = gameObject.transform;
// 获取 Transform 组件的 位置 , 旋转量 , 缩放倍数
Debug.Log("C# 脚本附着游戏物体的 Transform 组件数据 位置 : " + transform.position
+ " , 旋转量 : " + transform.rotation + " , 缩放倍数 : " + transform.localScale);
}
// Update is called once per frame
void Update()
{
}
}
回到 Unity 编辑器后 , 会自动编译上述修改后的 C# 脚本代码 ;
点击 Unity 编辑器 工具栏 右侧的 运行按钮
, 即可运行该 C# 组件 ;
Unity 中的 C# 脚本 , 都是 继承 MonoBehaviour 类 ;
public class BehaviourScript : MonoBehaviour
{
}
MonoBehaviour 类是在 UnityEngine 命名空间 下定义的 ;
using UnityEngine;
在本博客中所有用到的关于 Unity 的类 , 如
都定义在 UnityEngine 命名空间中 ;
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有