Unity3D学习笔记(二十):Rect、Canvas、Toggle、Slider、ScrollBar



框的显示:快捷键T

代码操作,继承Transform
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UGUI_RectTransform : MonoBehaviour {
public Canvas canvas;
//1、手动拖拽
private RectTransform rt;
// Use this for initialization
void Start () {
//2、获取方式
rt = GetComponent<RectTransform>();
//3、里氏转换原则
rt = transform as RectTransform;
//锚点坐标(物体中心点相对于锚点的坐标)
//rt.anchoredPosition = new Vector2(50, 100);
//世界坐标
//rt.position = Vector3.zero;
//相对于父物体坐标系的坐标, 跟锚点坐标不一样。
//rt.localPosition = new Vector2(50, 100);
//设置物体的宽高。只有四个点在一起组成锚点时使用
//rt.sizeDelta = new Vector2(500, 400);
//设置锚点
//rt.anchorMax = Vector2.one * 0.5f;
//rt.anchorMin = Vector2.one * 0.5f;
//当四个点不在一起组成锚框时
//设置的是Left和Bottom,界面的值就是100, 50
//rt.offsetMin = new Vector2(100, 50);
//设置的是Right和Top,界面的值是设置值的负值 -100 50
//rt.offsetMax = new Vector2(100, 50);
//设置中心点
rt.pivot = Vector2.one;
InstanceImage();
} // Update is called once per frame
void Update () {
//if (Input.GetMouseButton(0))
//{
// rt.anchoredPosition = new Vector2(500, 400);
//}
//if (Input.GetMouseButton(1))
//{
// rt.position = Vector3.zero;
//}
//if (Input.GetMouseButton(2))
//{
// rt.localPosition = new Vector2(50,100);
//}
}
void InstanceImage()//加载图片,默认生成在层级面板的根目录下
{
GameObject prefab = Resources.Load<GameObject>("prefab");
GameObject obj = Instantiate(prefab, canvas.transform);
}
}
----World Space(世界空间):只有该模式下Canvas的Rect Transorm才能编辑,并且纵深Z值有效了。


UnityEvent:Invoke方法也需要有一个bool类型的参数

UnityAction:无返回值的泛型委托,参数未指定

Toggle Group(单选框组):实现一组Toggle的单选效果,只有一个Group内的Toggle才是一个组。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UGUI_Slider : MonoBehaviour {
private Slider slider;
private float value = 0f;
// Use this for initialization
void Start () {
slider = GetComponent<Slider>();
//slider.value为实际的值
Debug.Log("Value: " + slider.value);
//slider.normalizedValue为值的百分比
Debug.Log("Value: " + slider.normalizedValue);
slider.value = 0f;
slider.onValueChanged.AddListener(AddValueChanged);
}
// Update is called once per frame
void Update () {
value += Time.deltaTime;
slider.value = value;
}
public void OnValueChanged(float value)
{
Debug.Log("手动添加的value:" + value);
}
private void AddValueChanged(float value)
{
Debug.Log("代码添加的value:" + value);
}
}
精灵图片批量添加动画:1、全选拖入,2、修改帧数

滑动值改为整数

代码操作
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UGUI_SliderMusic : MonoBehaviour {
private Slider slider;
private AudioSource source;
private void Awake()
{
source = gameObject.AddComponent<AudioSource>();
AudioClip clip = Resources.Load<AudioClip>("OnOff/SingleDog");
source.clip = clip;
source.Play();
slider = GetComponent<Slider>();
slider.onValueChanged.AddListener(OnValueChanged);
}
// Use this for initialization
void Start () {
slider.value = ;
} // Update is called once per frame
void Update () {
slider.value = ;
}
private void OnValueChanged(float value)
{
if (value > 0.5f)//打开音乐
{
source.volume = ;
}
else//关闭音乐
{
source.volume = ;
}
}
}
自制滚动条

OnValueChanged:可变参数


OnValueChanged(float):固定参数


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UGUI_ScrollBar : MonoBehaviour {
private Scrollbar bar;
// Use this for initialization
void Start () {
bar = GetComponent<Scrollbar>();
bar.value = 0.5f;//改变Scrollbar的值
bar.size = 0.4f;//改变句柄大小
bar.onValueChanged.AddListener(OnValueChanged);
} // Update is called once per frame
void Update () { }
public void OnValueChanged(float value)
{
Debug.Log("值变了:" + value);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UGUI_ScrollBar_Image : MonoBehaviour {
private Scrollbar bar;//滚动条
private RectTransform imageX;//图片
private float canvasX = 1920f;//画布
private float offset;//偏移量
private void Awake()
{
//
//GameObeject.Find();
//从子物体里寻找物体,参数是路径,并且支持层级结构
bar = transform.Find("Canvas/Scrollbar").GetComponent<Scrollbar>();
//通过方法找到物体的transform直接转换成Rect Transform
imageX = transform.Find("Canvas/Image") as RectTransform;
bar.onValueChanged.AddListener(OnValueChanged);
}
// Use this for initialization
void Start () {
// - (图片的宽度 - 画布的宽度)
offset = canvasX - imageX.sizeDelta.x;
//当图片宽度小于画布宽度时,滚动条没有意义,不需要显示
//offset 大于 0 的时候证明图片的宽度小于画布的宽度
if (offset >= )
{
bar.gameObject.SetActive(false);
}
else
{
bar.gameObject.SetActive(true);
}
bar.value = ;
} // Update is called once per frame
void Update () { }
//当Scroll bar的值改变时,执行的方法
private void OnValueChanged(float value)
{
//根据value的值去改变图片的位置
float posX = value * offset;
imageX.anchoredPosition = new Vector2(posX, imageX.anchoredPosition.y);
}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RectTransformTest : MonoBehaviour
{
public RectTransform leftImg; // 设置的是锚点
public RectTransform rightImg; // 设置的是锚框
public RectTransform upImg; // 设置的是水平锚线
public RectTransform downImg; // 设置的是垂直锚线
void Start()
{
// 设置图片的尺寸为 400,300
// 设置图片的位置为 父物体的中心位置
// ========================== leftImg 设置的是锚点
if (leftImg.anchorMin.x == leftImg.anchorMax.x && leftImg.anchorMin.y == leftImg.anchorMax.y)
{
// 设置位置
leftImg.anchoredPosition = Vector2.zero;
// 设置图片尺寸
leftImg.sizeDelta = new Vector2(, );
}
// ========================== rightImg 设置的是锚框
if (rightImg.anchorMin.x != rightImg.anchorMax.x && rightImg.anchorMin.y != rightImg.anchorMax.y)
{
// 设置位置
float anchorReferensePointX = ( - rightImg.pivot.x) * rightImg.anchorMin.x + rightImg.pivot.x * rightImg.anchorMax.x;
float anchorReferensePointY = ( - rightImg.pivot.y) * rightImg.anchorMin.y + rightImg.pivot.y * rightImg.anchorMax.y;
rightImg.anchoredPosition = rightImg.pivot - new Vector2(anchorReferensePointX, anchorReferensePointY);
// 设置图片尺寸
//rightImg.offsetMin = new Vector2(100, 100);
//rightImg.offsetMax = new Vector2(-100, -100);
rightImg.sizeDelta = new Vector2(-, -);
//Debug.Log("RightImg sizeDelta : " + rightImg.sizeDelta); // sizeDelta = offsetMax - offsetMin; 结果: (-200, -200)
}
// ========================== upImg 设置的是水平锚线 (上方)
if(upImg.anchorMin.y == upImg.anchorMax.y && upImg.anchorMin.x != upImg.anchorMax.x)
{
// 设置位置
float anchorReferensePointX = ( - upImg.pivot.x) * upImg.anchorMin.x + upImg.pivot.x * upImg.anchorMax.x;
float anchorReferensePointY = ( - upImg.pivot.y) * upImg.anchorMin.y + upImg.pivot.y * upImg.anchorMax.y;
Vector2 anchorPos = upImg.pivot - new Vector2(anchorReferensePointX, anchorReferensePointY);
RectTransform parentTrans = upImg.parent as RectTransform;
anchorPos.y -= parentTrans.rect.height / ;
upImg.anchoredPosition = anchorPos;
// 设置图片尺寸
upImg.offsetMin = new Vector2(, -);
upImg.offsetMax = new Vector2(-, -);
//upImg.sizeDelta = new Vector2(-200, 300);
}
// ========================== downImg 设置的是垂直锚线 (左方)
if (downImg.anchorMin.x == downImg.anchorMax.x && downImg.anchorMin.y != downImg.anchorMax.y)
{
// 设置位置
float anchorReferensePointX = ( - downImg.pivot.x) * downImg.anchorMin.x + downImg.pivot.x * downImg.anchorMax.x;
float anchorReferensePointY = ( - downImg.pivot.y) * downImg.anchorMin.y + downImg.pivot.y * downImg.anchorMax.y;
Vector2 anchorPos = downImg.pivot - new Vector2(anchorReferensePointX, anchorReferensePointY);
RectTransform parentTrans = downImg.parent as RectTransform;
anchorPos.x += parentTrans.rect.width / ;
downImg.anchoredPosition = anchorPos;
// 设置图片尺寸
downImg.offsetMin = new Vector2(, );
downImg.offsetMax = new Vector2(, -);
//downImg.sizeDelta = new Vector2(400, -200);
}
}
void Update()
{
}
}
补充内容-Unity的委托和事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events; // Unity中使用的委托和事件的命名空间
// C#中使用的委托
// using System; // Action、Action<T>、Action<T, A> .....Action<A, B, C, .....> 没有返回值的
// Func<TResult>、Func<T, TResult>、Func<A, B, .... TResult> 有返回值的
// Predicate<T> 有一个参数,返回值是bool类型
// Comparison<T>(T x, T y) 返回值是int型
public class UnityEventTest : MonoBehaviour
{
public UnityAction myAction;
public UnityEvent myEvent1; // 可以在检视面板中显示 用法同UI
public MyEvent2 myEvent2;
void Start()
{
#region Unity中提供的委托
// 没有返回值 没有参数 相当于C#中的 Action
UnityAction del1 = delegate ()
{
Debug.Log("delegate");
};
del1 += () => { Debug.Log("Lambda"); };
del1 += Fun1;
del1();
UnityAction<int> del2 = delegate (int num) { Debug.Log(num); };
// 有参的匿名委托,Unity委托中参数的个数最多4个
UnityAction<int, int, int, int> del3 = (a, b, c, d) => { Debug.Log(a + b + c + d); };
#endregion
#region Unity中的事件
UnityEvent myEvent = new UnityEvent();
// 注册方法
myEvent.AddListener(
() =>
{
Debug.Log("这是Unity中的事件");
}
);
myEvent.AddListener(Fun1);
// 取消注册
myEvent.RemoveListener(Fun1);
myEvent.RemoveAllListeners();//无返回值无参数的事件,匿名委托只能用RemoveAllListeners();
// 调用
myEvent.Invoke();
// Unity中有参数的事件 需要自己写一个类去继承 UnityEvent<T> 参数个数:最多4个
// 通过自己的类去创建对象
MyEvent2 myEvent2 = new MyEvent2();
// 注册和取消注册同上
// 调用
myEvent2.Invoke();
#endregion
}
void Update()
{
}
public void Fun1()
{
}
}
public class MyEvent2 : UnityEvent<int> { }
public class MyEvent3 : UnityEvent<int, float, bool, string> { }
Unity3D学习笔记(二十):Rect、Canvas、Toggle、Slider、ScrollBar的更多相关文章
- python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码
python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...
- python3.4学习笔记(二十五) Python 调用mysql redis实例代码
python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...
- python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法
python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...
- python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字
python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字在字符串里面插入指定分割符的方法,先把字符串变成list然后用join方法变成字符串str=' ...
- python3.4学习笔记(二十) python strip()函数 去空格\n\r\t函数的用法
python3.4学习笔记(二十) python strip()函数 去空格\n\r\t函数的用法 在Python中字符串处理函数里有三个去空格(包括'\n', '\r', '\t', ' ')的函数 ...
- (C/C++学习笔记) 二十四. 知识补充
二十四. 知识补充 ● 子类调用父类构造函数 ※ 为什么子类要调用父类的构造函数? 因为子类继承父类,会继承到父类中的数据,所以子类在进行对象初始化时,先调用父类的构造函数,这就是子类的实例化过程. ...
- (C/C++学习笔记) 二十二. 标准模板库
二十二. 标准模板库 ● STL基本介绍 标准模板库(STL, standard template library): C++提供的大量的函数模板(通用算法)和类模板. ※ 为什么我们一般不需要自己写 ...
- (C/C++学习笔记) 二十. 文件和流
二十. 文件和流 ● 文件的概念 文件(file) 一. C/C++语言将文件作为字节序列(sequence of characters)来对待,但从编码角度,或说从对字节信息的解释来看,文件分为:文 ...
- Unity3D学习笔记(十二):2D模式和异步资源加载
2D模式和3D模式区别:背景纯色,摄像机2D,没有深度轴 精灵图片设置 Normal map,法线贴图,更有立体感 Sprite (2D and UI),2D精灵贴图,有两种用途 1.当做UI贴图 2 ...
- Java基础学习笔记二十五 MySQL
MySQL 在dos中操作mysql 连接mysql命令: mysql -uroot -p密码 ,连接OK,会出现mysql> 对数据库的操作 创建一个库 create database 库名 ...
随机推荐
- (转)Elasticsearch聚合初探——metric篇
前言 ES中的聚合被分为两大类:Metric度量和bucket桶(原谅我英语差,找不到合适的词语.....就用单词来说吧!).说的通俗点,metric很像SQL中的avg.max.min等方法,而bu ...
- 安卓手机上微信无法打开Https网址的完美解决方案
1,第三方网站检测网站的SSL证书是否正确的安装 https://www.geocerts.com/ssl-checker,大概率你会看到下边的场景,一个证书链完整的警告,如果想知道我的基础配置是什么 ...
- [转]Tesseract-OCR (Tesseract的OCR引擎最先由HP实验室于1985年开始研发)
光学字符识别(OCR,Optical Character Recognition)是指对文本资料进行扫描,然后对图像文件进行分析处理,获取文字及版面信息的过程.OCR技术非常专业,一般多是印刷.打印行 ...
- IIS注册WEB服务扩展
.net framework和iis那个先装的?如果先装IIS,然后再装.net的话,没有问题.但是如果顺序反了的话,需要在命令行里面执行 C:\Windows\Microsoft.NET\Frame ...
- OBV_X3
{OBV_X3[背景]考虑到OBV_X03在情况1的时候,采用的是寻找波段线的同价K线,但是由于此种情况下必须使用CONST(C)或通过输入参数CONSTCC设定固定值,无法当前K线的CLOSE同时变 ...
- Lintcode: Find Peak Element
There is an integer array which has the following features: * The numbers in adjacent positions are ...
- unity Texture贴图纹理及相关属性
Texture资源是Unity3d游戏开发中用途最广泛的资源之一,被引用于诸如界面UI. Mesh模型 .粒子效果等.还有一些特殊的Texture资源,如:Movie Texture:视频资源.Ren ...
- webstorm的个性化设置settings
如何更改主题(字体&配色):File -> settings -> Editor -> colors&fonts -> scheme name.主题下载地址 如 ...
- 519. Random Flip Matrix(Fisher-Yates洗牌算法)
1. 问题 给定一个全零矩阵的行和列,实现flip函数随机把一个0变成1并返回索引,实现rest函数将所有数归零. 2. 思路 拒绝采样 (1)先计算矩阵的元素个数(行乘以列),记作n,那么[0, n ...
- python练习题,写一个方法 传进去列表和预期的value 求出所有变量得取值可能性(例如list为[1,2,3,4,5,6,12,19],value为20,结果是19+1==20只有一种可能性),要求时间复杂度为O(n)
题目:(来自光荣之路老师)a+b==valuea+b+c=valuea+b+c+d==valuea+b+c+d+...=valuea和b....取值范围都在0-value写一个方法 传进去列表和预期得 ...