Unity基础之UI插件

c#快捷键
ctrl+k+d-格式化
跟组件绑定的事件要自己写单独的函数
进到新工程里先把当前场景保存一下:Assets->Create->Folder->Scene(用来存当前场景)
1.创建画布:右键->Create->UI->Canvas(此时会自动出来EventSystem组件,内含Event                       System(Script)和Standalone Input Module(Script)用来处理事件的发送,接收等)
2.Canvas中Render Mode渲染模式:有Overlay(覆盖屏幕),Camera(相机视角),World三种)
3.Overlay两个特点:映射方式:会按一个像素对应一个单位长度的方式设置画布大小,此模式不需要u摄像机,永远出现在所有摄像机的最前面。【正式的游戏界面】Rect Transform里的属性无法修改
创建Canvas的主物体:Canvas->右键UI->Image
Anchors:锚点
Canvas Renderer:画布渲染器(不可修改)

*Image (script)(用来设置图片组件)中
图片转化成sprite(精灵图)拖到image里:两种情况
裁剪成多张图片:选中图片-》Texture Type-》Sprite (2D and UI)-》Sprite Mode-》Multiple(多张)-》Sprite Editor(编辑)->三角-》type-》Grid By Cell count-》几列几行-》slice-》插-》apple
如果是单张:选中图片-》Texture Type-》Sprite (2D and UI)-》Sprite Editor(编辑)->apple
然后,在Image-》点击生成的图片(拖)-》√Image (script)-》Source Image-》None (sprite)


Source Image:原图片 
想让一张图片再UGUI中使用必须Texture Type->Sprite(2D and uI)想使用哪张图片就把哪张图片拖到Image (script)->Source Image->None (Material材质)
或者Set Native size(设置本地大小:原图大小)
Color:起颜色叠加作用
Preserve Aspect:保持原本宽高比时勾上
Image Type:图片类型(四种)
simple:简单模式(系统默认)
Tiled:堆叠模式
Sliced:切片模式。点图片->Sprite Mode->Multiple->Apply
Filled:填充模式
Fill Method:填充方法  
Horizontal:水平
Vertical:竖直
Radial 360:360度的放射状
Fill Origin:填充的初始位置
Fill Amount:填充的比列/数量  
Bottom:底部
Clockwise:填充时的方向(勾上顺时针,不勾逆时针)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestImageFilled : MonoBehaviour
{
    //冷却时间
    public folat coldTime = 2;
    //当前图片的Image组件
    Image selfImage;
    // Start is called before the first frame update
    void Start()
    {
        //获取当前图片的Image组件
        selfImage = this.GetComponent<Image>();
        //设置当前图片类型为填充
        selfImage.type = Image.Type.Filed;
        //设置当前图片的填充方法
        selfImage.fillMethod = selfImage.FillMethod.Radial1360;
        //设置当前图片的填充初始位置
        selfImage.fill0rigin = 2;
        //设置当前图片的填充比例
        selfImage.fillAmount = 0;

    }

    // Update is called once per frame
    void Update()
    {
        //如果填充比例小于1
        if(selfImage.fillAmount < 1)
        {

            selfImage.fillAmount += (1.0F/coldTime*coldTime.deltaTime);
        }
    }
}


*Text组件
Text (Script):文字属性
Character:字体相关
Font:字体(选中需要的字体拖进框中)
windows提供常见字体:C:\Windows\Fonts(.OTF或.TTF)
Font Style:字体风格
    Normal:正常
    Bold:加粗
    ltalic:斜体
    Bold And Italic:加粗斜体
Line Spacing:行边距
Rich Text:副文本编辑(可对部分内容进行加粗或斜体)
例如:
<b>New Text大家好New</b> <i>Text大家好</i><color="red">New Text大家好</color>
Paragraph:段落
   Alignment:对齐
Align By Geometr:按几何体对齐
Horizontal Overflow:水平方向溢出
    wrap:回卷,换行
Vertical Overflow:垂直方向溢出
    Truncate:截短(竖直方向能显示多少就显示多少)
Best Fit:自适应(勾上可设字体大小范围)
Material:材质
Raycast Target:再射线机制中当前文本框是否作为射线的目标(默认打勾,是)

*计时器

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.WSA;
using System;

public class TimerText : MonoBehaviour
{
    //当前文本框的字体文件
    public Font targetFont;
    //当前文本框的text组件
    private Text selfText;
    //计时器
    private float timer;
    // Start is called before the first frame update
    void Start()
    {
        //获取当前文本框的text组件
        selfText = this.GetComponent<Text>();
        //指定字体
        selfText.font = targetFont;
        //指定字号
        selfText.fontSize = 40;
        //指定字体格式
        selfText.fontStyle = FontStyle.Normal;
        //指定字体颜色
        selfText.color = Color.red;
        //指定字体的对齐格式
        selfText.alignment = TextAnchor.MiddleCenter;


        //是否支持富文本编辑
        selfText.supportRichText = true;
        //初始时即使为0
        timer = 0;


    }

    // Update is called once per frame
    void Update()
    {
        //计时器逐帧计时
        timer += Time.deltaTime;
        //将以秒为单位的计时转换为TimeSpan类型
        TimeSpan tempTimeSpan = new TimeSpan(0, 0, (int)timer);
        //显示当前的计时
        selfText.text = tempTimeSpan.Hours.ToString("00") + ":" +
           "<color=\"yellow\">" + tempTimeSpan.Minutes.ToString("00") +"</color>"+ ":" +
            "<color=\"cyan\">" + tempTimeSpan.Seconds.ToString("00") + "</color>";


    }
}

*按钮组件:Button (script)
Interactable:视图可交互
Transition:过渡,指多个状态的随意切换


  Normal Color:普通时的状态
  Highlighted Color:高亮时的状态
  Pressed Color:按下按钮时的状态
  Disabled Color:禁用时的状态
  Fade Duration:颜色渐变的周期
  Color Multiplier:颜色放大倍数(会使颜色变浅)

Button:
Transition:sprite swap
Target Graphic:正常状态
  Animation:动画的过度
Auto Generate Anir ation;自动产生动画->新建文件夹为:Anim->新建文件夹,名字随意(用来存储动画 )
这时主栏会自动添加一个Animator(动画)组件

Window->Animation->Animation
Normal:正常
再做一个跟 之前按钮效果一模一样的按钮:UI->Button->Button(Script)里Transition:Animation->add...  搜Animation->把之前的拖到Animation的Controller里

Navigation:ui导航(当一个界面中存在多个按钮的时候允许使用键盘上的上下左右键在多个按钮之间进行选择切换)
Explicit:自定义
on click:
通过界面添加:点击+可添加函数
首先要配置物体的接受对象。把东西拖动到第二行
使图片变为原始大小Image.Setlativesize
Gameobject.name:点击后变名字
GameObject->SetActive (bool)
变为Gameobject.setActive:布尔类型函数(控制按钮是否禁用)
调整物体在子物体的使用顺序:
RectTransform->SetSiblinglndex (int)
变为RectTransform.setsiblingInde...
想让它第几就n-1
改图片:
lmage->Sprite sprite
变为Image.sprite
想继承于某个画布
RectTransform->SetParent (Transform)->把父级画布拖动到框中
通过脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventTestButton : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick()
    {

        print("该按钮被点击");
    }


}

再点击+->EventTestButton.EventTes


    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick(int m)
    {
        print(m);
    }

    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick(string str)
    {

        print(str);
    }

 //方法,当前按钮被点击之后的操作
 public void EventTestButtonClick(GameObject target)
 {
     //名字,位置,内容
     print(target.name);
     print(target.transform.position);
     print(target.GetComponent<Text>().text);
 }


替换
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EventTestButton : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        this.GetComponent<Button>().onClick.AddListener(EventTestButtonClick);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick()
    {
        print("按钮被点击");
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EventTestButton : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        this.GetComponent<Button>().onClick.AddListener(()=>EventTestButtonClick(456));
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick(int m)
    {        
        print(m);
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EventTestButton : MonoBehaviour
{
    public GameObject targetGameobject;
    // Start is called before the first frame update
    void Start()
    {
        this.GetComponent<Button>().onClick.AddListener(()=>EventTestButtonClick(targetGameobject));
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当前按钮被点击之后的操作
    public void EventTestButtonClick(GameObject target)
    {
        //名字,位置,内容
        print(target.name);
        print(target.transform.position);
        print(target.GetComponent<Text>().text);

    }


}


*Toggle开关组件:
换开关的背景颜色:Toggle->Background->Image (script)->Color
对勾有无:
换开关的背景颜色:Toggle->Background->checkmark
开关旁边的文字:Label
√Toggle (script)
Interactable:表示组件是否可交互
Transition:过渡
Color Tint:颜色过渡、
Sprite Swap:图片过渡
Animation:动画过渡
Is On:反应当前项是否被选择
Toggle Transition:对勾出现和消失是马上消失还是渐变消失
选择要消失的东西是什么(可以是背景可以是对勾):Graphic
on Value Changed (Boolean);当它的值发生变化有选中变为未选中,即值发生变化


动态函数:TestToggle->Dynamic bool上的->ToggleValueChanged

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestToggle : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当该选择框的值发生切换时,执行该操作
    public void ToggleValueChanged(bool isSelected)
    {
        //该选项被选中
        if (isSelected)
        {
            print("该选项被选中");
        }
        //否则
        else
        {
            print("该选项未被选中2");
        }

    }
}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestToggle : MonoBehaviour
{
    //该物体的Toggle组件
    private Toggle selfToggle;


    // Start is called before the first frame update
    void Start()
    {
        //该物体的Toggle组件
        selfToggle = this.GetComponent<Toggle>();
        //添加Toggle组件的事件
        selfToggle.onValueChanged.AddListener(ToggleValueChanged);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //方法,当该选择框的值发生切换时,执行该操作
    public void ToggleValueChanged(bool isSelected)
    {
        //该选项被选中
        if (isSelected)
        {
            print("该选项被选中");
        }
        //否则
        else
        {
            print("该选项未被选中2");
        }

    }
}

Group:
canvas->Create Empty->Add Component->Toggle Group->锁住->选中要单选的开关拖到Group里->解锁
是否允许空选:Allow Switch off(勾中为必选一个)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ColorGroup : MonoBehaviour
{

    //本物体的ToggleGroup
    private ToggleGroup selfToggleGroup;
    // Start is called before the first frame update
    void Start()
    {
        //获取本物体的开关组件
        selfToggleGroup = this.GetComponent<ToggleGroup>();

        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //方法,当前toggleGroup的状态发生改变时,改变该方法
    public void ToggleGrouoStateChanged()
    {
        print("状态改变");
    }
}


滑动栏: slider(用于血条)
scrollbar(用于地图缩放)
InputField(用于用户和密码输入框)
Panel面板(游戏背景)
   Fill Rect:划过区域的颜色
  Handle Rect:进度条的手柄
  Direction:滑动的方向
  Min Value:最小值
  Max Value:最大值
  whole Numbers:勾上取整数值

Background:长条背景
Fill Area:填充区域,设置锚点
Fill:划过区域的颜色
Hanave slide:手柄区域,设置锚点
Handle:手柄的颜色


Dropdown:下拉栏
Label:文本组件
Arrow:箭头
Template:模板
ui->input field文本输入框

wn:下拉栏
Label:文本组件
Arrow:箭头
Template:模板
ui->input field文本输入框

PointerEnter:鼠标进入
PointerExit:鼠标离开
PointerUp:鼠标按上
PointerDown:鼠标离开
Pointerclick:鼠标点击
Drag::拖动进行中
BeginDrag:刚开始拖动
EndDrag:结束拖动

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestPanel : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler,IPointerUpHandler,IPointerDownHandler,IPointerClickHandler
{
    //当前游戏物体的image组件
    private Image selfImage;
    //当前图片的初始颜色
    private Color originColor;


    // Start is called before the first frame update
    void Start()
    {
        //获取当前游戏物体组件
        selfImage = this.GetComponent<Image>();
        //记录当前图片的初始颜色
        originColor = selfImage.color;

    }

    // Update is called once per frame
    void Update()
    {
        
    }
    //当鼠标进入该图片范围时,执行该方法
    public void OnMouseEnter()
    {
        //图片颜色变为绿色
        selfImage.color = Color.green;
    }

    //当鼠标离开该图片范围时,执行该方法
    public void OnMouseExit()
    {
        //图片颜色
        selfImage.color = originColor;
    }

    //当鼠标按按下该图片范围时,执行该方法
    public void MouseDown()
    {
        //图片颜色
        this.transform.localScale = 0.8F * Vector3.one;
    }
    //当鼠标按松开该图片范围时,执行该方法
    public void MouseUp()
    {
        //图片颜色
        this.transform.localScale = Vector3.one;
    }
    //当鼠标被点击该图片范围时,执行该方法
    public void MouseClick()
    {
        print("图片被点击");
    }

    //当鼠标开始拖动图片时
    public void MouseBeginDrag()
    {
        this.transform.localScale = 0.8F * Vector3.one;
        print("begindrag");
        //当前图片位置变为当前鼠标位置
        this.transform.position = Input.mousePosition;

    }

    //当鼠标正在拖动图片时
    public void MouseIsDragging()
    {

        print("dragging");
        //图片跟随鼠标位置
        this.transform.position = Input.mousePosition;

    }

    //当鼠标结束拖动图片时
    public void MouseendDrag()
    {

        print("enddrag");
        this.transform.localScale = Vector3.one;
    }
    //在当前图片范围内滚动鼠标滚轮
    public void MouseScroll()
    {

        print("鼠标滚动");
    }
    //IPointerEnterHandler
    public void OnPointerEnter(PointerEventData eventData)
    {
        //图片颜色变为绿色
        selfImage.color = Color.green;
    }
    //IPointerExitHandler  离开
    public void OnPointerExit(PointerEventData eventData)
    {
        //图片颜色
        selfImage.color = originColor;
    }
    //IPointerUpHandler
    public void OnPointerUp(PointerEventData eventData)
    {
        this.transform.localScale = Vector3.one;
    }
    //IPointerDownHandler
    public void OnPointerDown(PointerEventData eventData)
    {
        this.transform.localScale = 0.8F * Vector3.one;
    }
    //IPointerClickHandler
    public void OnPointerClick(PointerEventData eventData)
    {
        print(21);
    }
}

登录背景图片:Panel->√Raw Image (script)-》选择背景图片-》Texture->None (Texture)
放logo:Panel->ui->lmage->选图片->Sprite Mode->single->拖->lmage->Source lmage->None (Sprite)
logo文字:Panel->ui->Text
Window->Package Manager
登录框:Panel->ui->Panel->Source Image->选图片-录背景图片:Panel->√Raw Image (script)-》选择背景图片-》Texture->None (Texture)
放logo:Panel->ui->lmage->选图片->Sprite Mode->single->拖->lmage->Source lmage->None (Sprite)
logo文字:Panel->ui->Text
Window->Package Manager
登录框:Panel->ui->Panel->Source Image->选图片->点登录框->TEXT
用户框:登录框->ul->lnput Field->lmage->Source lmage->选图片
密码同理
三个按钮:
给背景加音乐:Add Component->Audio Source->Audio Source->AudioClip
设置按钮交互:设置按钮->on click->➕->空白处->Create Empty->新建脚本->放Create Empty

代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class uiManager : MonoBehaviour
{
    //设置框
    public GameObject settingPanel;
//打开设置面板
    public void openSettingPanel()
    {
        settingPanel.SetActive(true);
    }

}

点击设置按钮:把Create Empty拖->设置按钮的on Click函数第二行->选函数方法
把设置框拖进Create Empty里setting panel里
设置栏关闭:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class uiManager : MonoBehaviour
{
    //设置框
    public GameObject settingPanel;
    //打开设置面板
    public void openSettingPanel()
    {
        settingPanel.SetActive(true);
    }
    //关闭设置面板
    public void closeSettingPanel()
    {
        settingPanel.SetActive(false);
    }
设置关闭栏->on click->+->函数->把代码的放到第二行->选方法


}


控制音量开关:根据ison控制
PublicManager-》UI Manager (Script)-》音量开关拖到Pause Music-》在音量开关中On Value Changed (Boolean)-》第二行PublicManage-》选方法-》UlManager-》PauseMusic 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class uiManager : MonoBehaviour
{
    //设置框
    public GameObject settingPanel;
    //背景音乐
    public AudioSource bgMusic;
    //音量滑动条
    public Slider volumeSlider;
    //音乐开关
    public Toggle pauseMusic;

  

    //打开设置面板
    public void openSettingPanel()
    {
        settingPanel.SetActive(true);
    }
    //关闭设置面板
    public void closeSettingPanel()
    {
        settingPanel.SetActive(false);
    }

    public void changeVolume()
    {
       
       
        //设置背景音乐音量大小
        bgMusic.volume = volumeSlider.value;

    }
    public void PauseMusic()
    {
        if (pauseMusic.isOn)
        {
            bgMusic.Play();
        }
        else
        {
            bgMusic.Pause();
        }

    }
}

登录
publicmanager-》用户名拖到user Name-》密码拖到Password-》登录信息拖到Login Info
登录按钮-》 on click-》PublicManage拖到第二行-》选方法

assets-》scenes-》文件game-》file-》buildsetting-》把两个场景都拖进去 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class uiManager : MonoBehaviour
{
    //设置框
    public GameObject settingPanel;
    //背景音乐
    public AudioSource bgMusic;
    //音量滑动条
    public Slider volumeSlider;
    //音乐开关
    public Toggle pauseMusic;
    //用户名
    public InputField userName;
    //密码
    public InputField password;
    //登录信息
    public Text LoginInfo;


    //打开设置面板
    public void openSettingPanel()
    {
        settingPanel.SetActive(true);
    }
    //关闭设置面板
    public void closeSettingPanel()
    {
        settingPanel.SetActive(false);
    }

    public void changeVolume()
    {
       
       
        //设置背景音乐音量大小
        bgMusic.volume = volumeSlider.value;

    }
    public void PauseMusic()
    {
        if (pauseMusic.isOn)
        {
            bgMusic.Play();
        }
        else
        {
            bgMusic.Pause();
        }

    }

    public void Login()
    {
        //获取用户名
        string user_text = userName.text;
        string pwd_text = password.text;
            //验证用户和密码是否正确
            if(user_text.Trim().Equals("admin") && pwd_text.Trim().Equals("123456"))
        {
            //跳转场景
            SceneManager.LoadScene("game");

        }
        else
        {

            LoginInfo.text = "用户名或密码错误";
        }

    }

}

退出

在退出按钮中事件里加方法


//退出
    public void ExitGame()
    {
        Application.Quit();
    }


背包
Canvas-》image->选好大小放格子背景图片

页面切换:On Click ()-》第一行Editor And Runtime-》第二行让这个按钮跟某一个东西进行捆绑-》GameObject-》SetActive (bool)

Slider
音量大小
PublicManager-》Bg Music-》背景->volume slider->音量控制条

音量条-》


背包系统
一. ui模板搭建
二.物品属性设计
1创建一个类物品类
2. int id
string物品名称
string 物品说明
三.物品生成方法
三.拖动使用物品

四. ui模板搭建
ui->Canvas(支撑整个ui的显示和隐藏)
EventSystem是一个事件系统。想用ui必须有它
做两个面板(角色面板和背包面板)ui->Panel
做两个按钮(角色和背包)
做四个装备格子:角色面板-》ui->Gameobject-》ui->image-》放图片-》ui->text
角色属性显示:角色面板下-》ui-》text
字体阴影:Add Component-》shadow-》x5,y5
背包格子-》背包面板-》Gameobject-》ui-》image
格子布局:背包格子-》Add Component-》Grid Layout Group (Script)
控制一行放几个
Grid Layout Group (Script)-》Constraint-》Fixed Column Count-》数量(一行几个)
角色按钮:on click()-》第二行角色面板-》右边GameObject-》SetActive-》下面√
背包按钮相同
背包面板×按钮:背包面板-》ui-》button
onclick-》第二行背景面板-》右边GameObject-》SetActive-》下面不打√
角色面板×按钮相同
格子里面的图片-》复制一个image拖到-》image1里-》选图片
物品数量-》图片-》ui-》text

二.物品属性设计
1创建一个类物品类
5. int id
string物品名称
string 物品说明
添加按钮
建脚本-》物品类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class wupinlei : MonoBehaviour
{
    public int id;
    public string mingcheng;//物品名称
    public string shuoming;//物品说明
    public fenlei leibie;//物品分类  物品类别
    public int jiage;

    public enum fenlei
    {
        yaopin,
        wuqi,
        fangjv,
        xiaohaopin,

    }
}

建脚本:加载游戏物品
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class jiazaiyouxiwupin : MonoBehaviour
{
    public static jiazaiyouxiwupin jiazaidanli;//加载单例
    public List<wupinlei> youxiwupin = new List<wupinlei>();//游戏物品
    public List<wupinlei> wanjiawupin = new List<wupinlei>();//玩家物品
    public TextAsset wupinshujv;//物品数据
    public string[] wupinstring;
    public string[] wupinshuxing;
    // Start is called before the first frame update
    void Start()
    {
        jiazaidanli = this;
       wupinshujv=Resources.Load("youxishujv") as TextAsset;
        //获取的数据拆成数组
       wupinstring = wupinshujv.text.Split('\n');
        foreach(var item in wupinstring)
        {
           string[] wupinshuxing = item.Split(',');
            youxiwupin.Add(new wupinlei(){id=Convert.ToInt32(wupinshuxing[0]),mingcheng=wupinshuxing[1],shuoming=wupinshuxing[2],jiage= Convert.ToInt32(wupinshuxing[3])});

        }
    }
    public void wanjiatianjiawupin(int aid)
    {
        wanjiawupin.Add(youxiwupin.Where(t=>t.id==aid).First());
        
    }
    public void wanjiayichuwupin(int aid)
    {
        wanjiawupin.Remove(youxiwupin.Where(t => t.id == aid).First());

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Assets-》Resources-》youxishujv.txt
1000,帽子,这是一个帽子,100
1001,鞋子,这是一个鞋子,100
1002,裤子,这是一个裤子,100
1003,红药水,这是一个红药水,100
1004,蓝药水,这是一个蓝药水,100
测试:
背包内部格子:Canvas-》panel背包面板-》Image背包格子-》放背景图片-》复制格子-》点背包面板设布局-》Add Component->Grid Laygut Group-》再背包格子里建一个image-》放物品图片
克隆:->用代码克隆预制体ces->把ces脚本挂载到canvas->把需要克隆的预制体拖到与ces脚本相同的路径中(图标变蓝即为预制体)->把预制体拖进(canvas->ces脚本->第二行yuzhiti'里)->启动游戏
ces脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ces : MonoBehaviour
{
    public GameObject yuzhiti;

    // Start is called before the first frame update
    void Start()
    {
        //克隆预制体
        Instantiate(yuzhiti);
    }

    // Update is called once per frame
    void Update()
    {    }
}
父物体:canvas->父物体拖->运行
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ces : MonoBehaviour
{
    public GameObject yuzhiti;
    public Transform fuwuti;//父物体

    // Start is called before the first frame update
    void Start()
    {
        //把克隆预制体给到go
        GameObject go=Instantiate(yuzhiti);
        //设置父物体
        go.transform.SetParent(fuwuti);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
canvas->背包面板->背包格子->image->tag->add tag...->+->添加标签背包格子->代码:添加物品里->背包按钮->on click->第二行main camera->右边jiazaiyouxiwupin->wanjiadakaibeibao
代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class jiazaiyouxiwupin : MonoBehaviour
{
    public static jiazaiyouxiwupin jiazaidanli;//加载单例
    public List<wupinlei> youxiwupin = new List<wupinlei>();//游戏物品
    public List<wupinlei> wanjiawupin = new List<wupinlei>();//玩家物品
    public TextAsset wupinshujv;//物品数据
    public string[] wupinstring;
    public string[] wupinshuxing;
    public GameObject wupinmoban;//物品模板
    public GameObject[] beibaogezi;//背包格子
    // Start is called before the first frame update
    void Start()
    {
        jiazaidanli = this;
        //背包格子
        beibaogezi = GameObject.FindGameObjectsWithTag("beibaogezi");

       wupinshujv=Resources.Load("youxishujv") as TextAsset;
        //获取的数据拆成数组
       wupinstring = wupinshujv.text.Split('\n');
        foreach(var item in wupinstring)
        {
           string[] wupinshuxing = item.Split(',');
            youxiwupin.Add(new wupinlei(){id=Convert.ToInt32(wupinshuxing[0]),mingcheng=wupinshuxing[1],shuoming=wupinshuxing[2],jiage= Convert.ToInt32(wupinshuxing[3])});

        }

       
    }
    //玩家打开背包
    public void wanjiadakaibeibao()
    {
        if (wanjiawupin.Count>0)
        {
            //声明变量
            int bianhao = 0;
            foreach(var item in wanjiawupin)
            {
                //克隆模板
                GameObject go = Instantiate(wupinmoban);
                //给模板找一个父对象
                go.transform.SetParent(beibaogezi[bianhao].transform);
                bianhao++;

            }

           
        }

    }

    public void wanjiatianjiawupin(int aid)
    {
        wanjiawupin.Add(youxiwupin.Where(t=>t.id==aid).First());
        
    }
    public void wanjiayichuwupin(int aid)
    {
        wanjiawupin.Remove(youxiwupin.Where(t => t.id == aid).First());

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
main camera->jiazaiyouxiwupin->(resources的游戏数据挂载到)youxishujv里
*image-》tag选beibaogezi

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class jiazaiyouxiwupin : MonoBehaviour
{
    public static jiazaiyouxiwupin jiazaidanli;//加载单例
    public List<wupinlei> youxiwupin = new List<wupinlei>();//游戏物品
    public List<wupinlei> wanjiawupin = new List<wupinlei>();//玩家物品
    public TextAsset wupinshujv;//物品数据
    public string[] wupinstring;
    public string[] wupinshuxing;
    public GameObject wupinmoban;//物品模板
    public GameObject[] beibaoge;//背包格子
    public GameObject beibaojiemian;
    // Start is called before the first frame update
    void Start()
    {
        jiazaidanli = this;
        

       wupinshujv=Resources.Load("youxishujv") as TextAsset;
        //获取的数据拆成数组
       wupinstring = wupinshujv.text.Split('\n');
        foreach(var item in wupinstring)
        {
           string[] wupinshuxing = item.Split(',');
            youxiwupin.Add(new wupinlei(){id=Convert.ToInt32(wupinshuxing[0]),mingcheng=wupinshuxing[1],shuoming=wupinshuxing[2],jiage= Convert.ToInt32(wupinshuxing[3])});

        }
        //运行后自动添加物品
        for(int i = 0; i < 3; i++)
        {
            wanjiatianjiawupin(1000);
        }
        for (int i = 0; i < 3; i++)
        {
            wanjiatianjiawupin(1001);
        }
        for (int i = 0; i < 3; i++)
        {
            wanjiatianjiawupin(1002);
        }
        for (int i = 0; i < 3; i++)
        {
            wanjiatianjiawupin(1003);
        }


    }
    //玩家打开背包
    public void wanjiadakaibeibao()
    {
        //背包格子,标签为背包格子的物体赋值
        beibaoge = GameObject.FindGameObjectsWithTag("beibaogezi");

        foreach(var item in beibaoge)
        {
            if (item.transform.childCount > 0)
            {
                Destroy(item.transform.GetChild(0).gameObject);

            }


        }


        if (wanjiawupin.Count>0)
        {
            //声明变量
            int bianhao = 0;
            foreach(var item in wanjiawupin)
            {
                //克隆模板
                GameObject go = Instantiate(wupinmoban);
                //给模板找一个父对象
                go.transform.SetParent(beibaoge[bianhao].transform);
                go.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
                Text wupinmingcheng = go.GetComponentInChildren<Text>();
                wupinmingcheng.text = wanjiawupin[bianhao].mingcheng;
                bianhao++;

            }

           
        }

    }

    public void wanjiatianjiawupin(int aid)
    {
        wanjiawupin.Add(youxiwupin.Where(t=>t.id==aid).First());
        //背包界面激活就
        if (beibaojiemian.activeSelf)
        {
            wanjiadakaibeibao();
        }
    }
    public void wanjiayichuwupin(int aid)
    {
        wanjiawupin.Remove(youxiwupin.Where(t => t.id == aid).First());
        //背包界面激活就
        if (beibaojiemian.activeSelf)
        {
            wanjiadakaibeibao();
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

物品跟随鼠标
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class cesi : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        GameObject go = eventData.pointerCurrentRaycast.gameObject;
        print(go.name);
        print("开始拖动");
    }

    public void OnDrag(PointerEventData eventData)
    {
        GameObject go = eventData.pointerCurrentRaycast.gameObject;
        //跟随鼠标
        go.transform.position = Input.mousePosition;
     
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        print("拖动结束");
    }
}

背包:新
canvas->image(bag)背景图->image(girds)格子
介绍(拓展框):image(bag)背景图->image(b3)
背包唤出:
canvas->button(xbag)->宝箱图片->on click(让button跟bag进行捆绑)第二行bag->第一行editor and runtime->右GameObject->SetActive (bool)->✔
bag关闭按钮:canvas->bag->button(×)->图片->on click(跟bag进行绑定)第二行bag->第一行editor and runtime->右GameObject->SetActive (bool)->不打勾
脚本Playermove:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Playermove : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        openmybag();
    }
    private bool isOpen;
    public GameObject mybag;//我的背包项目
    //背包控制
    void openmybag()
    {
        isOpen = mybag.activeSelf;
        if (Input.GetKeyDown("c"))
        {

            isOpen = mybag.activeSelf;

            if (Input.GetKeyDown("c"))
            {
                isOpen = !isOpen;
                mybag.SetActive(isOpen);
            }

        }

    }

}
panel(player)->playmove脚本拖进去->mybag里拖bag(按c键控制背包栏)

assets->solts->goodsitem(goodsitem脚本)和inventory(inventory脚本)->同级Create->lnventory(New goodsitem)一级衣服
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName ="New goodsitem",menuName ="inventory/New gooditem")]
public class goodsitem : ScriptableObject

{
    //武器名字
    public string itemname;
    //武器实体:照片
    public Sprite itemsprite;
    //武器数量
    public int itemheld;
    //武器详情
    [TextArea]//设为多行
    public string iteminfo;

}

inventory
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New inventory", menuName = "inventory/New inventory")]
public class inventory : ScriptableObject
{

   public List<goodsitem> goodsitems = new List<goodsitem>();

    
}

inventory里create->inventory->new inventory(goodsbag)->goodsbag->Goodsitems->size->1->Element ->yijiyifu (goodsitem)拖入
在solts里新建脚本->goodsonworld->代码->Assets > Solts->Create->Folder->

bag->新建panel画布(grids)->放bag下->以前的grids改为b2->grids下新建image->grids里add component->Grid Layout Group->Spacing两个格子的距离->在solts->goods里->slot


控制3D物体,鼠标跟随,键盘移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class move : MonoBehaviour
{

    //控制移动速度
    public float speed = 1.5f;
    public Transform go;
    void Start()
    {
        go = this.transform;
    }

    void Update()
    {

        FollowMouseRotate();
        FollowMouseMove();

        向左
        if (Input.GetKey(KeyCode.A))
        {
            go.Translate(Vector3.left * Time.deltaTime * speed);

        }
        //向左
        if (Input.GetKey(KeyCode.D))
        {
            go.Translate(Vector3.right * Time.deltaTime * speed);

        }
        //向左
        if (Input.GetKey(KeyCode.W))
        {
            go.Translate(Vector3.forward * Time.deltaTime * speed);

        }
        //向左
        if (Input.GetKey(KeyCode.S))
        {
            go.Translate(Vector3.back * Time.deltaTime * speed);

        }

        //物体跟随鼠标旋转
        void FollowMouseRotate()
        {
            //获取鼠标的坐标,鼠标是屏幕坐标,Z轴为0,这里不做转换  
            Vector3 mouse = Input.mousePosition;
            //获取物体坐标,物体坐标是世界坐标,将其转换成屏幕坐标,和鼠标一直  
            Vector3 obj = Camera.main.WorldToScreenPoint(transform.position);
            //屏幕坐标向量相减,得到指向鼠标点的目标向量,即黄色线段  
            Vector3 direction = mouse - obj;
            //将Z轴置0,保持在2D平面内  
            direction.z = 0f;
            //将目标向量长度变成1,即单位向量,这里的目的是只使用向量的方向,不需要长度,所以变成1  
            direction = direction.normalized;
            //物体自身的Y轴和目标向量保持一直,这个过程XY轴都会变化数值  
            transform.up = direction;
        }


        //跟随鼠标移动
        void FollowMouseMove()
        {
            float moveSpeed = 3.0f;
            if (Input.GetMouseButton(0))    //如果按下鼠标左键,移动速度变快
            {
                moveSpeed = 6.0f;
                transform.Translate(Vector3.up * moveSpeed * Time.deltaTime);
            }
            else
            {
                transform.Translate(Vector3.up * moveSpeed * Time.deltaTime);
            }
        }

    }

}

跟随鼠标移动
 void Update()
    {


        //首先获取到当前物体的屏幕坐标
        Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
        //让鼠标的屏幕坐标的Z轴等于当前物体的屏幕坐标的Z轴,也就是相隔的距离
        Vector3 m_MousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, pos.z);
        //将正确的鼠标屏幕坐标换成世界坐标交给物体
        transform.position = Camera.main.ScreenToWorldPoint(m_MousePos);

}

跟随鼠标
using UnityEngine;
public class Move3DObject : MonoBehaviour
{
    private bool isClick = false;
    private Transform curTf = null;
    private Vector3 oriMousePos;
    private Vector3 oriObjectScreenPos;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 100))
            {
                curTf = hit.transform;
                oriObjectScreenPos=Camera.main.WorldToScreenPoint(curTf.position);
                oriMousePos = Input.mousePosition;
            }
            isClick = !isClick;
        }
        if (isClick)
        {
            if (curTf != null)
            {
                Vector3 curMousePos = Input.mousePosition;
                Vector3 mouseOffset = curMousePos - oriMousePos;
                Vector3 curObjectScreenPos = oriObjectScreenPos + mouseOffset;
                Vector3 curObjectWorldPos = Camera.main.ScreenToWorldPoint(curObjectScreenPos);
                curTf.position = curObjectWorldPos;
            }
        }
    }
}


鼠标拖拽2dimage鼠标跟随

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class image : MonoBehaviour, IDragHandler
{
    public void OnDrag(PointerEventData eventData)
    {
        GameObject image = eventData.pointerDrag;
        image.transform.position = Input.mousePosition;
    }

}


Resources-》Create-》Folder
检测下面是否是背包格子:物品模板-》canvas group-》Blocks Raycasts✔
选中所有图片:Horizontal Layout Group(Script)

滚动条:
Elasticity  弹性
Unrestricted:不做限制
Clamped:限制
Inertia:惯性
Deceleration Rate:减速的快慢0.135(指华东惯性的大小)
Deceleration Rate:滚动灵敏度
viewport:视野
Horizontal Scrollbar:水平滚动条
vertical Scrollbar:竖直滚动条


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值