转 UnityEngine.Input.GetKey(string name)方法参数表

本文提供了一个Unity中用于检测键盘按键的脚本示例。该脚本定义了一系列按键名称,并在每帧更新时检查这些按键是否被按下,如果检测到按键被按下,则会在控制台输出该按键的名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:https://blog.youkuaiyun.com/qq_21397217/article/details/84859320

UnityEngine.Input.GetKey(string name)方法参数表
原文:https://answers.unity.com/questions/762073/c-list-of-string-name-for-inputgetkeystring-name.html
参考:https://docs.unity3d.com/ScriptReference/KeyCode.html

按键名称及测试脚本:

using UnityEngine;

public class Test : MonoBehaviour
{
    private string[] keyNames = new string[]
    {
        // 辅助键
        "left shift", "right shift",
        "left ctrl", "right ctrl",
        "left alt", "right alt",
        // 空格键
        "space",
        // 方向键
        "up", "down", "right", "left",
        // 取消键
        "escape",
        // f1~f15键
        "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8",
        "f9", "f10", "f11", "f12", "f13", "f14", "f15",
        // 数字键
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        // 字母键
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
        "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        // 符号键(没有 “~” 和 “%”)
        "`", "!", "@", "#", "$", "^", "&", "*", "(", ")", "-", "_", "=", "+",
        "[", "]", "\\", ";", ":", "'", "\"", ",", "<", ".", ">", "/", "?",
        // 编辑键
        "tab", "backspace", "delete",
        "home", "end", "insert",
        "page up", "page down",
        // 锁定键
        "caps lock",
        "numlock",
        "scroll lock",
        // 其他键
        "pause", "clear", "return",
    };

    private void Update()
    {
        foreach (var keyName in keyNames)
        {
            if (Input.GetKeyDown(keyName))
            {
                Debug.Log(keyName);
            }
        }
    }
}
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Collections.Generic; using System; using UnityEngine; using XLua; //配置的详细介绍请看Doc下《XLua的配置.doc》 public static class ExampleGenConfig { //lua中要使用到C#库的配置,比如C#标准库,或者Unity API,第三方库等。 [LuaCallCSharp] public static List<Type> LuaCallCSharp = new List<Type>() { typeof(System.Object), typeof(UnityEngine.Object), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Quaternion), typeof(Color), typeof(Ray), typeof(Bounds), typeof(Ray2D), typeof(Time), typeof(GameObject), typeof(Component), typeof(Behaviour), typeof(Transform), typeof(Resources), typeof(TextAsset), typeof(Keyframe), typeof(AnimationCurve), typeof(AnimationClip), typeof(Animation), typeof(Animator), typeof(MonoBehaviour), typeof(ParticleSystem), typeof(SkinnedMeshRenderer), typeof(Renderer), typeof(WWW), typeof(System.Collections.Generic.List<int>), typeof(Action<string>), typeof(UnityEngine.Debug), typeof(BoxCollider), typeof(Mathf), typeof(UnityEngine.Random), //typeof(Input), typeof(Screen), typeof(Shader), typeof(Material), typeof(SpriteRenderer), }; //C#静态调用Lua的配置(包括事件的原型),仅可以配delegate,interface [CSharpCallLua] public static List<Type> CSharpCallLua = new List<Type>() { typeof(Action), typeof(Func<double, double, double>), typeof(Action<string>), typeof(Action<double>), typeof(UnityEngine.Events.UnityAction), }; //黑名单 [BlackList] public static List<List<string>> BlackList = new List<List<string>>() { new List<string>(){"UnityEngine.WWW", "movie"}, new List<string>(){ "UnityEngine.MonoBehaviour", "runInEditMode"}, new List<string>(){ "UnityEngine.MonoBehaviour", "useGUILayout"}, new List<string>(){"UnityEngine.Texture2D", "alphaIsTransparency"}, new List<string>(){"UnityEngine.Security", "GetChainOfTrustValue"}, new List<string>(){"UnityEngine.CanvasRenderer", "onRequestRebuild"}, new List<string>(){"UnityEngine.Light", "areaSize"}, new List<string>(){"UnityEngine.AnimatorOverrideController", "PerformOverrideClipListCleanup"}, new List<string>(){"UnityEngine.Input", "IsJoystickPreconfigured"}, #if !UNITY_WEBPLAYER new List<string>(){"UnityEngine.Application", "ExternalEval"}, #endif new List<string>(){"UnityEngine.GameObject", "networkView"}, //4.6.2 not support new List<string>(){"UnityEngine.Component", "networkView"}, //4.6.2 not support new List<string>(){"System.IO.FileInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.FileInfo", "SetAccessControl", "System.Security.AccessControl.FileSecurity"}, new List<string>(){"System.IO.DirectoryInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.DirectoryInfo", "SetAccessControl", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "CreateSubdirectory", "System.String", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "Create", "System.Security.AccessControl.DirectorySecurity"}, }; }
07-07
using System.Collections.Generic; using UnityEngine; using TMPro; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine.EventSystems; public class DialogueManager : MonoBehaviour { public enum DialogueState { Before, Win, Lost } public static DialogueManager Instance; [Header("UI Elements")] public TextMeshProUGUI tmpText; public float typingSpeed = 0.05f; [Header("Dialogue Content")] public List<string> beforeBattleDialogues = new List<string>(); public List<string> winDialogues = new List<string>(); public List<string> lostDialogues = new List<string>(); [Header("场景布置")] public GameObject image; public GameObject image1; public GameObject image2; public TextMeshProUGUI text; [Header("按钮设置")] public Button startButton; public Button loseButton; public Button winButton; private bool isTyping = false; private Coroutine typingCoroutine; private string currentSentence; public DialogueState currentState = DialogueState.Before; private int currentDialogueIndex = 0; private List<string> currentDialogueList; void Start() { // 隐藏所有按钮 // 检查战斗结果 int result = PlayerPrefs.GetInt("LastBattleResult", -1); if (result == 1) { Debug.Log("战斗胜利 - 触发胜利对话"); SetDialogueState(DialogueState.Win); } else if (result == 0) { Debug.Log("战斗失败 - 触发失败对话"); SetDialogueState(DialogueState.Lost); } else { Debug.Log("首次进入 - 默认对话"); SetDialogueState(DialogueState.Before); } // 清除状态 PlayerPrefs.DeleteKey("LastBattleResult"); } void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); } // 初始化当前对话列表 currentDialogueList = beforeBattleDialogues; // 设置按钮点击事件 startButton?.onClick.RemoveAllListeners(); loseButton?.onClick.RemoveAllListeners(); winButton?.onClick.RemoveAllListeners(); if (startButton != null) startButton.onClick.AddListener(OnStartClick); if (loseButton != null) loseButton.onClick.AddListener(OnLoseClick); if (winButton != null) winButton.onClick.AddListener(OnWinClick); } void Update() { // 添加跳过功能:按E键跳过当前打字效果 if (Input.GetKeyDown(KeyCode.E) && isTyping) { SkipTyping(); } // 按E键继续下一句对话 else if (Input.GetKeyDown(KeyCode.E) && !isTyping && tmpText.gameObject.activeSelf) { NextSentence(); } } // 隐藏所有按钮 // 设置当前对话状态 public void SetDialogueState(DialogueState newState) { currentState = newState; currentDialogueIndex = 0; switch (newState) { case DialogueState.Before: currentDialogueList = beforeBattleDialogues; break; case DialogueState.Win: currentDialogueList = winDialogues; break; case DialogueState.Lost: currentDialogueList = lostDialogues; break; } Debug.Log($"状态已切换至: {newState}"); } // 启动当前状态的对话 public void StartStateDialogue() { if (currentDialogueList == null || currentDialogueList.Count == 0) return; // 如果正在显示其他文本,先停止 if (isTyping) { StopCoroutine(typingCoroutine); } // 确保索引在有效范围内 currentDialogueIndex = Mathf.Clamp(currentDialogueIndex, 0, currentDialogueList.Count - 1); currentSentence = currentDialogueList[currentDialogueIndex]; // 暂停玩家移动 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = false; // 锁定玩家输入 Cursor.lockState = CursorLockMode.None; Cursor.visible = true; // 显示对话框UI tmpText.gameObject.SetActive(true); // 启动打字效果协程 typingCoroutine = StartCoroutine(TypeSentence(currentSentence)); } // 显示下一句对话 public void NextSentence() { currentDialogueIndex++; if (currentDialogueIndex < currentDialogueList.Count) { StartStateDialogue(); } else { // 对话结束 EndDialogue(); } } IEnumerator TypeSentence(string sentence) { isTyping = true; tmpText.text = ""; // 逐字显示 foreach (char letter in sentence.ToCharArray()) { tmpText.text += letter; yield return new WaitForSeconds(typingSpeed); } isTyping = false; } // 跳过当前打字效果 public void SkipTyping() { if (isTyping) { StopCoroutine(typingCoroutine); tmpText.text = currentSentence; isTyping = false; } } public void EndDialogue() { if (isTyping) { StopCoroutine(typingCoroutine); isTyping = false; } // 恢复玩家控制 playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; // 隐藏对话框 tmpText.gameObject.SetActive(false); // 根据状态显示对应按钮 switch (currentState) { case DialogueState.Before: if (startButton != null) startButton.gameObject.SetActive(true); break; case DialogueState.Win: if (winButton != null) winButton.gameObject.SetActive(true); break; case DialogueState.Lost: if (loseButton != null) loseButton.gameObject.SetActive(true); break; } // 确保事件系统可用 EnsureEventSystemExists(); // 设置按钮为选中状态 if (currentState == DialogueState.Before && startButton != null) { EventSystem.current.SetSelectedGameObject(startButton.gameObject); } else if (currentState == DialogueState.Win && winButton != null) { EventSystem.current.SetSelectedGameObject(winButton.gameObject); } else if (currentState == DialogueState.Lost && loseButton != null) { EventSystem.current.SetSelectedGameObject(loseButton.gameObject); } } private void EnsureEventSystemExists() { EventSystem eventSystem = FindObjectOfType<EventSystem>(); if (eventSystem == null) { GameObject eventSystemObj = new GameObject("EventSystem"); eventSystem = eventSystemObj.AddComponent<EventSystem>(); eventSystemObj.AddComponent<StandaloneInputModule>(); } else if (eventSystem.GetComponent<StandaloneInputModule>() == null) { eventSystem.gameObject.AddComponent<StandaloneInputModule>(); } } private void OnMainMenuClick() { Debug.Log("主菜单按钮点击"); SceneManager.LoadScene("MainMenu"); } private void OnStartClick() { Debug.Log("开始作战"); SceneManager.LoadScene("Fight"); } private void OnLoseClick() { Debug.Log("失败按钮点击"); SceneManager.LoadScene("Fight"); } private void OnWinClick() { if (currentState != DialogueState.Win) { Debug.LogWarning("尝试在非胜利状态执行胜利逻辑"); return; } playercontrol player = FindObjectOfType<playercontrol>(); if (player != null) player.canMove = true; Debug.Log("执行胜利逻辑"); image.SetActive(false); image1.SetActive(false); image2.SetActive(false); text.gameObject.SetActive(false); tmpText.gameObject.SetActive(false); winButton.gameObject.SetActive(false); } }using UnityEngine; [System.Serializable] public class GameData { // 玩家位置数据 public Vector3 playerPosition; // 场景名称 public string currentScene; // 存档时间戳 public string saveTime; // 构造函数 public GameData() { playerPosition = Vector3.zero; currentScene = "MainMenu"; saveTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm"); } } using System.IO; using UnityEngine; public class SaveSystem : MonoBehaviour { public static SaveSystem Instance { get; private set; } public GameData currentData { get; private set; } private string savePath; private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); Initialize(); } else { Destroy(gameObject); } } private void Initialize() { savePath = Path.Combine(Application.persistentDataPath, "savedata.json"); LoadGame(); } // 保存游戏 public void SaveGame(Vector3 playerPosition) { currentData.playerPosition = playerPosition; currentData.currentScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; currentData.saveTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm"); string jsonData = JsonUtility.ToJson(currentData); File.WriteAllText(savePath, jsonData); Debug.Log($"游戏已保存: {savePath}"); } // 加载游戏 public void LoadGame() { if (File.Exists(savePath)) { string jsonData = File.ReadAllText(savePath); currentData = JsonUtility.FromJson<GameData>(jsonData); } else { currentData = new GameData(); } } // 删除存档 public void DeleteSave() { if (File.Exists(savePath)) { File.Delete(savePath); currentData = new GameData(); } } // 检查存档是否存在 public bool SaveExists() { return File.Exists(savePath); } } 我想在原有的功能下实现添加储存当前的state
最新发布
08-08
现在我来说一下目前的情况,首先我的系统目前结构是Config(GridConfig.cs),Core(GridData.cs,GridObjectType.cs,TerrainType.cs),DataModels(ChessData.cs,GridCell.cs,StructureData.cs,TerrainConfig.cs,TerrainData.cs,TokenData.cs),Initialization(GameInitializer.cs),Managers(GameDataManager.cs,GridManager.cs,TerrainGenerator.cs),Objects(GirdObject.cs,StructureObject.cs,TerrainObject.cs),GridBugView.cs,InputHandler.cs,然后Scene目前是GameManager(搭载GameInitializer(没拖拽TerrainGenerator,DataManager)和GameDataManager),GridSystem(GirdManager(已拖动Config,Tilemap,DefaultTile为None)和TerrainGenerator(已拖动Tilemap,Config,DefaultTerrain为null)),Grid(Tilemap)这些,然后sprite地形我做了几个,分别是Terrains(结构为空物体搭载sprite)和它的Forest, Grass, Village,Water变体,tag什么的都没设置呢,然后人物也是一样的结构但不是Terrains的变体,只做了一个叫TestCharacter,别的先不做,你看着办吧,然后有非常多的报错,你先看看代码然后给我一个整理之后的正确可运行版本,告诉我都需要做什么using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; namespace gridstudy { [CreateAssetMenu(menuName = "Grid/GridConfig")] public class GridConfig : ScriptableObject { public int GridWidth = 10; public int GridHeight = 10; public TileBase DefaultTile; [SerializeField] private List<TerrainConfig> _terrainConfigs = new List<TerrainConfig>(); [Header("Prefabs")] public GameObject TerrainPrefab; public GameObject StructurePrefab; public GameObject ChessPrefab; public GameObject TokenPrefab; public TerrainConfig GetTerrainConfig(TerrainType type) { return _terrainConfigs.Find(c => c.type == type); } public List<TerrainConfig> GetAllTerrainConfigs() { return new List<TerrainConfig>(_terrainConfigs); } } }using System.Collections.Generic; using UnityEngine; namespace gridstudy { [System.Serializable] public class GridData { public int width; public int height; public GridCell[,] cells; public GridData(int w, int h) { width = w; height = h; cells = new GridCell[w, h]; } } }namespace gridstudy { public enum GridObjectType { Terrain, Structure, Chess, Token } }namespace gridstudy { public enum TerrainType { Grass, Water, Mountain, Forest, Desert, Road } }using System.Collections; using UnityEngine; namespace gridstudy { // ChessData.cs [CreateAssetMenu(menuName = "Unit/ChessData")] public class ChessData : ScriptableObject { public string unitName; public int moveRange; public int attackPower; } }using System.Collections.Generic; using UnityEngine; namespace gridstudy { [System.Serializable] public class GridCell { public Vector2Int coordinate; public TerrainData terrain; // TODO: 实现以下类 public StructureData structure; public ChessData chess; public List<TokenData> tokens; public GridCell(Vector2Int coord) { coordinate = coord; tokens = new List<TokenData>(); } } }using System.Collections; using UnityEngine; namespace gridstudy { [CreateAssetMenu(menuName = "Structure/StructureData")] public class StructureData : ScriptableObject { public string structureName; public int health; public int buildCost; } }using UnityEngine; using UnityEngine.Tilemaps; namespace gridstudy { [CreateAssetMenu(menuName = "Terrain/TerrainConfig")] public class TerrainConfig : ScriptableObject { public TerrainType type; public TileBase tile; public int movementCost = 1; public bool isWalkable = true; public bool isBuildable = false; } }using UnityEngine; namespace gridstudy { [System.Serializable] public class TerrainData { public TerrainType type; public Vector2Int coordinate; public int variantIndex; [System.NonSerialized] public bool isOccupied; } }using System.Collections; using UnityEngine; namespace gridstudy { [CreateAssetMenu(menuName = "Item/TokenData")] public class TokenData : ScriptableObject { public string itemName; public Sprite icon; } }using UnityEngine; namespace gridstudy { public class GameInitializer : MonoBehaviour { [SerializeField] private TerrainGenerator _terrainGenerator; [SerializeField] private GameDataManager _dataManager; void Start() { if (!_dataManager.LoadGame()) InitializeNewGame(); GridData gridData = _dataManager.GetGridData(); _terrainGenerator.InitializeGrid(gridData.width, gridData.height); } private void InitializeNewGame() { GridData newGrid = new GridData(10, 8); _dataManager.SetGridData(newGrid); } void OnApplicationQuit() { _dataManager.SaveGame(); } } }using UnityEngine; namespace gridstudy { public class GameDataManager : MonoBehaviour { private const string SAVE_KEY = "GridData"; private GridData _currentGridData; public void SaveGame() { if (_currentGridData == null) return; string jsonData = JsonUtility.ToJson(_currentGridData); PlayerPrefs.SetString(SAVE_KEY, jsonData); PlayerPrefs.Save(); Debug.Log("Game data saved successfully"); } public bool LoadGame() { if (PlayerPrefs.HasKey(SAVE_KEY)) { string jsonData = PlayerPrefs.GetString(SAVE_KEY); _currentGridData = JsonUtility.FromJson<GridData>(jsonData); Debug.Log("Game data loaded successfully"); return true; } return false; } public GridData GetGridData() => _currentGridData; public void SetGridData(GridData data) => _currentGridData = data; // 在 GameDataManager 中添加 public void SaveFullGameState() { // 收集所有网格对象数据 foreach (var cell in _currentGridData.cells) { if (cell.terrain != null) SaveTerrainData(cell.terrain); if (cell.structure != null) SaveStructureData(报错)(cell.structure); } // 保存到PlayerPrefs(实际项目应使用文件存储) PlayerPrefs.SetString("GameState", JsonUtility.ToJson(_currentGridData)); } private void SaveTerrainData(TerrainData data) { // 实现具体保存逻辑 } } }using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; namespace gridstudy { public class GridManager : MonoBehaviour { [SerializeField] private GridConfig _config; [SerializeField] private Tilemap _terrainTilemap; [SerializeField] private TileBase _defaultTile; private GridCell[,] _gridData; private Dictionary<Vector2Int, List<GridObject>> _objectsMap = new(); private Dictionary<GridObjectType, GameObject> _prefabMap; void Awake() { // 初始化prefab映射 _prefabMap = new Dictionary<GridObjectType, GameObject> { { GridObjectType.Terrain, _config.TerrainPrefab }, { GridObjectType.Structure, _config.StructurePrefab }, { GridObjectType.Chess, _config.ChessPrefab }, { GridObjectType.Token, _config.TokenPrefab } }; } public void GenerateGrid(int width, int height) { _gridData = new GridCell[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { _gridData[x, y] = new GridCell(new Vector2Int(x, y)); Vector3Int tilePos = new Vector3Int(x, y, 0); _terrainTilemap.SetTile(tilePos, _defaultTile); } } } public GridCell GetCellData(Vector2Int coord) { return _gridData[coord.x, coord.y]; } public void PlaceObject<T>(GridObjectType type, Vector2Int gridPos, T data) where T: ScriptableObject { if (!_prefabMap.TryGetValue(type, out GameObject prefab)) return; GameObject instance = Instantiate(prefab, GridToWorld(gridPos), Quaternion.identity); GridObject gridObject = instance.GetComponent<GridObject>(); gridObject.GridPosition = gridPos; // 更新数据层 GridCell cell = GetCellData(gridPos); switch (type) { case GridObjectType.Terrain: cell.terrain = data as TerrainData; break; case GridObjectType.Structure: cell.structure = data as StructureData; break; // ...其他类型处理 } if (!_objectsMap.ContainsKey(gridPos)) _objectsMap[gridPos] = new List<GridObject>(); _objectsMap[gridPos].Add(gridObject); gridObject.OnPlaced(); } private Vector3 GridToWorld(Vector2Int gridPos) { return new Vector3(gridPos.x + 0.5f, gridPos.y + 0.5f, 0); } } }using UnityEngine; using UnityEngine.Tilemaps; namespace gridstudy { public class TerrainGenerator : MonoBehaviour { [Header("References")] [SerializeField] private Tilemap _terrainTilemap; [SerializeField] private GridConfig _gridConfig; [Header("Terrain Settings")] [SerializeField] private TerrainConfig _defaultTerrain; private TerrainType[,] _terrainLayout; private GridData _gridData; public void InitializeGrid(int width, int height) { _gridData = new GridData(width, height); _terrainLayout = new TerrainType[width, height]; GenerateBaseTerrain(); RenderTerrainToTilemap(); } private void GenerateBaseTerrain() { for (int x = 0; x < _gridData.width; x++) { for (int y = 0; y < _gridData.height; y++) { _gridData.cells[x, y] = new GridCell(new Vector2Int(x, y)); TerrainType terrainType = GetTerrainTypeForPosition(x, y); _terrainLayout[x, y] = terrainType; _gridData.cells[x, y].terrain = new TerrainData { type = terrainType, coordinate = new Vector2Int(x, y), variantIndex = Random.Range(0, 3) }; } } } private TerrainType GetTerrainTypeForPosition(int x, int y) { if (x == 0 || y == 0 || x == _gridData.width - 1 || y == _gridData.height - 1) return TerrainType.Water; return TerrainType.Grass; } private void RenderTerrainToTilemap() { for (int x = 0; x < _gridData.width; x++) { for (int y = 0; y < _gridData.height; y++) { Vector3Int tilePos = new Vector3Int(x, y, 0); TerrainType type = _gridData.cells[x, y].terrain.type; TerrainConfig config = _gridConfig.GetTerrainConfig(type); _terrainTilemap.SetTile(tilePos, config != null ? config.tile : _defaultTerrain.tile); } } } public TerrainConfig GetTerrainConfig(Vector2Int coord) { if (IsValidCoordinate(coord)) { TerrainType type = _gridData.cells[coord.x, coord.y].terrain.type; return _gridConfig.GetTerrainConfig(type); } return null; } private bool IsValidCoordinate(Vector2Int coord) { return coord.x >= 0 && coord.x < _gridData.width && coord.y >= 0 && coord.y < _gridData.height; } } }using UnityEngine; namespace gridstudy { public abstract class GridObject : MonoBehaviour { public GridObjectType ObjectType { get; protected set; } public Vector2Int GridPosition { get; set; } public virtual void OnPlaced() { } public virtual void OnRemoved() { } } }using System; using UnityEngine; namespace gridstudy { public class StructureObject : GridObject { public event Action<StructureObject> OnStructureDestroyed; private void Awake() { ObjectType = GridObjectType.Structure; } public override void OnPlaced() { // 建筑放置逻辑 } } }using UnityEngine; namespace gridstudy { public class TerrainObject : GridObject { [SerializeField] private SpriteRenderer _renderer; public void Initialize(TerrainData data, TerrainConfig config) { Data = data; _renderer.sprite = config.tile.sprite; // 从Tile获取Sprite(报错) } } }using gridstudy; using System.Collections; using UnityEngine; namespace gridstudy { // 网格调试视图 public class GridDebugView : MonoBehaviour { [SerializeField] private GridManager _gridManager; [SerializeField] private bool _showGrid = true; void OnDrawGizmos() { if (!_showGrid || _gridManager == null) return; for (int x = 0; x < _gridManager.GridWidth; x++) { for (int y = 0; y < _gridManager.GridHeight; y++) { Gizmos.DrawWireCube( new Vector3(x + 0.5f, y + 0.5f, 0), Vector3.one ); } } } } }using UnityEngine; namespace gridstudy { public class InputHandler : MonoBehaviour { [SerializeField] private Camera _mainCamera; [SerializeField] private GridManager _gridManager; void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 worldPos = _mainCamera.ScreenToWorldPoint(Input.mousePosition); Vector2Int gridPos = new Vector2Int( Mathf.FloorToInt(worldPos.x), Mathf.FloorToInt(worldPos.y) ); // 示例:在点击位置创建草地 TerrainData terrainData = ScriptableObject.CreateInstance<TerrainData>();(报错) terrainData.type = TerrainType.Grass; terrainData.coordinate = gridPos; _gridManager.PlaceObject(报错)( GridObjectType.Terrain, gridPos, terrainData ); } } } }
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值