本文主要用于给新人提供实现剧情类游戏的基本思路。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
然后是一个很重要的
[System.Serializable]
它的作用是使得在检查器窗口来看到我i们自己创建的类从而实现在检查器直接进行故事剧情的书写(当然如果你写个脚本通过excle 表进行写也行)
然后写一个剧情数据类
public class StoryData
{
public string story;//故事文本
public string[] choicestory;//选择的故事文本;
public int[] nextindices;// 下一段剧情的索引数据;
}
然后是 故事控制类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StoryController : MonoBehaviour
{
public void OnChoiceMade(int index)
{
switch (index) // 根据索引判断玩家做出了什么选择
{
case 1: // 如果玩家选择了第一个选项
Debug.Log("You chose to 1"); // 输出日志信息
break;
case 2: // 如果玩家选择了第二个选项
Debug.Log("You chose to 2"); // 输出日志信息
break;
case 3: // 如果玩家选择了第三个选项
Debug.Log("You chose to 3"); // 输出日志信息
break;
case 4: // 如果玩家选择了第四个选项
Debug.Log("You chose to 4."); // 输出日志信息
break;
default:
break;
}
}
}
他的作用是报错了方便查找同时 还可以写其他功能实现扩展。
接下来是剧情展示类
讲一下思路
public class StoryDisplay : MonoBehaviour
{
public StoryData[] storyDatas; // 剧情数据数组
public Text storyText; // 显示故事文本的UI组件
public Button[] choiceButtons; // 显示选择按钮的UI组件数组
private int currentIndex = 0; // 当前剧情索引
private StoryController storyController; // 剧情控制器
void Start()
{
storyController = FindObjectOfType<StoryController>(); // 查找场景中唯一存在的StoryController组件
Refresh(); // 刷新界面
}
void Refresh()
{
if (currentIndex >= 0 && currentIndex < storyDatas.Length) // 如果当前索引有效
{
StoryData data = storyDatas[currentIndex]; // 获取当前段落对应的数据对象
storyText.text = data.storyText; // 显示故事文本
for (int i = 0; i < choiceButtons.Length; i++) // 遍历所有按钮
{
Button button = choiceButtons[i];
if (i < data.choiceTexts.Length) // 如果有对应的选择文本
{
button.gameObject.SetActive(true); // 激活按钮
button.GetComponentInChildren<Text>().text = data.choiceTexts[i]; // 显示选择文本在按钮上
int nextIndex = data.nextIndices[i];
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => OnClickChoiceButton(nextIndex));
}
else
{
button.gameObject.SetActive(false);
}
}
}
else
{
storyText.text = "The End.";
}
}
void OnClickChoiceButton(int nextIndex)
{
currentIndex = nextIndex; // 更新当前索引
storyController.OnChoiceMade(currentIndex); // 通知剧情控制器玩家做出了选择
Refresh(); // 刷新界面
}
}
为什么发文助手总说让我提供代码 我这不都已经发了一堆了么。。。。。