【金台的游戏开发常用代码】

文章介绍了Unity3D中实现单例模式的方法,以及如何通过名字和标签查找游戏对象。此外,还涉及到GameObject的组件获取、脚本交互,以及通过委托和事件进行类间通信。同时,文章提到了使用LitJson进行网络请求和JSON数据解析的基本操作。

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

单例模式

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    public static T instance
    {
        get;
        private set;
    }

    private void Awake()
    {
        if (instance == null)
        {
            instance = (T)this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}

静态

public class Demo : MonoBehaviour
{
    public static Demo instance;

    private void Awake()
    {
        instance = this;
    }

查找物体

public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public void findObject()
{
    //通过名字查找
    cube2 = GameObject.Find("Cube");
    GameObject.Find("A/B/Cube");
    //通过标签查找
    cube3 = GameObject.FindWithTag("tag");
}
//创建物体后查找
//着重标明GetComponent 获取物体上的组件
   public GameObject Prefab;
   public Transform transform;
   //引用下面的文件,获取asset中的值
    public PanelControl panelControl;
    public void myItem(TextGame_ItemName itemName)
    {
    	//创建物体
        GameObject go=Instantiate(Prefab, transform);
       
        //查找创建的prefab下的      
        go.transform.Find("Image").GetComponent<Image>().sprite =
            panelControl.GetPanelItem(itemName).itemSprite;
        go.transform.Find("Text").GetComponent<TextMeshProUGUI>().text = 
            ""+panelControl.GetPanelItem(itemName).itemName;
        //物体脚本
        go.GetComponent<脚本名>().参数名 = "";                                
    }

右键自定义 创建asset文件

[CreateAssetMenu(fileName ="Panel_Item_So",menuName = "Inventory/Panel_Item_So", order =1)]
public class PanelControl : ScriptableObject
{
    public List<PanelItemDetails> itemDetailslist;

    //获取名称获取物品
    public PanelItemDetails GetPanelItem(TextGame_ItemName itemName)
    {
        //定义了一个临时变量i,并将物品的名称赋值给i
        return itemDetailslist.Find(i => i.itemName == itemName);
    }
}


[System.Serializable]
public class PanelItemDetails
{
    //名称
    public TextGame_ItemName itemName;
    //图片
    public Sprite itemSprite;
}

public enum TextGame_ItemName
{
    苹果,Money
}

可视化list和键盘输入
list和字典最大的区别:字典Dictionary有key值,直接找key值就可以了
//上面的枚举,SerializeField为序列化可视化,但是字典不能直接序列化

[SerializeField] private List<TextGame_ItemName> list = new List<TextGame_ItemName>();
 private void Update()
    {
         if (Input.GetKeyDown(KeyCode.Q))
 {
            //要测试的方法
            
 }
    }
//移动位置
public GameObject Prefabs = null;
     private GameObject go;
    
     private void mytransform(GameObject btn)
    {

       //原来位置
        Vector3 pos = btn.transform.localPosition;
        Vector3 pos2;
        pos2 = new Vector3(-(pos.x + 500), 32, 0);
        pos2 = new Vector3(pos2.x,-(pos.y-32), 0);
         //将prefab移动一点距离
        go.transform.localPosition = pos2;
       
   }

事件
注:事件只能在类中声明,委托可以在类外声明
Action是一个委托,可直接拿来用的
所以事件是添加了限制的委托

//事件的准备
public static class EventHandler{
     public static event Action<ABC> TestEvent;
    public static void CallTestEvent(ABC abc)
    {
        TestEvent?.Invoke(abc);
    }
}

//呼叫,什么时候可以进行事件
public class A:MonoBehaviour{
   EventHandler.CallTestEvent(abc); 
}


//注册事件,事件的具体实现
public class AManager : Singleton<AManager>{
     private void OnEnable()
    {
        EventHandler.TestEvent += OnItemUsedEvent;
    }

    private void OnDisable()
    {
        EventHandler.TestEvent -= OnItemUsedEvent; 
    }

    private void OnItemUsedEvent(ABC obj)
    {
        //进行操作
    }
}

循环
foreach(var i in list)

协程(死循环)

 private void Start()
    {

        this.StartCoroutine(enumerator());
    }
    
 IEnumerator enumerator()
    {
        while (true)
        {
            yield return new WaitForSeconds(3);
            //要做的操作
        }
    }

接口
//接口

public interface IGameData
{
    //如果不需要返回值的话自然是void,save和read也都不需要了
    GameData IGameDataSo();
    void SaveData()
    {
    //实际操作是建立一个list进行保存数据
        SaveLoadManager.instance.SaveData(this);
    }

    void ReadData(GameData gamedataso);
}

网络请求–工具LitJson(这里使用的是这个)和Newtonsoft

https://www.jianshu.com/p/4bfbdf7cd240 litjson 学习json

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using LitJson;

public class HttpGetTest : MonoBehaviour
{
 //json内容为
{"code":200,"message":"成功!","result":{"name":"粉河不语堕秋晓。","from":"吴文英《秋蕊香·七夕》"}}
    [TextArea]
    public string json;

    // Start is called before the first frame update
    void Start()
    {
        httpUtils(json);
    }

    private void httpUtils(string str)
    {
        myjson myjsontext =  JsonMapper.ToObject<myjson>(str);

        Debug.Log("解析" + myjsontext.code);
        Debug.Log("解析" + myjsontext.message);
        //注意,这里的类名和调用名必须一致
        Debug.Log("解析" + myjsontext.result.name);
        Debug.Log("解析" + myjsontext.result.from);
    }

    IEnumerator GetText()
    {
        //获取名言的接口api,谢谢这位兄弟peakchao
        //博客地址https://blog.youkuaiyun.com/c__chao/article/details/78573737
        string url = "https://api.apiopen.top/api/sentences";
        UnityWebRequest quest = UnityWebRequest.Get(url);
        yield return quest.SendWebRequest();

        Debug.Log("请求返回" + quest.result);
        if (quest.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("请求失败"+quest.error);
        }
        else
        {
            Debug.Log("请求成功"+quest.downloadHandler.text);
            httpUtils(quest.downloadHandler.text);
        }
    }

    //[System.Serializable]
    public class myjson
    {
        public int code;
        public string message;
        //注意,这里的类名和调用名必须一致
        public result result;
    }

    //[System.Serializable]
    public class result
    {
        public string name;
        public string from;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值