文章目录
- 1 交互事件——更改 Cube 颜色
- 2 交互事件——创建 Cube
- 2.1 非代码方式
- 2.2 代码方式
在开始操作前,我们导入上次操作的场景,相关介绍在 《2024-04-08 NO.5 Quest3 手势追踪进行 UI 交互-CSDN博客》 文章中。
1 交互事件——更改 Cube 颜色
(1)在场景中创建一个方块 Cube,修改其缩放大小。
(2)在 Button 上添加脚本 “Interactable Unity Event Wrapper”,并关联如下引用。
- Interactable View
<--
“Poke Interactable” 脚本。

(3)在 When Hover() 中添加事件,并关联上 Cube 物体。选择 MeshRenderer > Material material。并将材质球 Red 进行关联。


(4)同样的方式对 When Select() 进行操作,关联 Blue 材质。对 When Unselect() 关联 Default-Material。

此时运行程序,即可点击按钮实现更改 Cube 颜色的功能。
2 交互事件——创建 Cube
2.1 非代码方式
首先复制一份按钮。
(1)创建如下脚本 ItemSpawner.cs。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemSpawner : MonoBehaviour
{
public GameObject spawnObj;
public Transform spawnPoint;
// Start is called before the first frame update
void Start() { }
// Update is called once per frame
void Update() { }
public void SpawnItem() {
Object.Instantiate(spawnObj, spawnPoint.position, spawnPoint.rotation);
}
}
(2)将 ItemSpawner.cs 挂载到 Button (2) 上。同时创建一个空物体,用于决定新 Cube 的生成位置,并赋值相关引用。

(3)在 “Interactable Unity Event Wrapper” 脚本中,新建 When Select() 事件,关联 “ItemSpawner” 脚本,选择 ItemSpawner > SpawnItem。

此时运行程序,即可点击按钮实现创建新 Cube 的功能。
2.2 代码方式
将 ItemSpawner.cs 脚本内容改为如下即可。
using System.Collections;
using System.Collections.Generic;
using Oculus.Interaction;
using UnityEngine;
public class ItemSpawner : MonoBehaviour
{
public GameObject spawnObj;
public Transform spawnPoint;
private InteractableUnityEventWrapper _eventWrapper;
// Start is called before the first frame update
void Start() {
_eventWrapper = GetComponent<InteractableUnityEventWrapper>();
_eventWrapper.WhenSelect.AddListener(SpawnItem);
}
// Update is called once per frame
void Update() { }
public void SpawnItem() {
Object.Instantiate(spawnObj, spawnPoint.position, spawnPoint.rotation);
}
}