Unity_给滚动视图动态添加子物体_066

来源:互联网 发布:局域网协作软件 编辑:程序博客网 时间:2024/06/02 05:32

ScrollView 的父子层次如下:
这里写图片描述
在ScrollView中添加的组件如下
这里写图片描述
在ViewPort中添加的组件如下:
这里写图片描述
在Content中添加的组件如下:
这里写图片描述

在ScrollView 中绑定的脚本如下:

using UnityEngine;using System.Collections;using UnityEngine.UI;using UnityEngine.EventSystems;using System;public class ScrollViewTest : MonoBehaviour,IBeginDragHandler,IEndDragHandler {    private ScrollRect scrollRect;    private float[] rateArr;    //获取Content的RectTransform    private RectTransform contentTransform;    //设置添加的预制体    public RectTransform itemTransform;    // Use this for initialization    void Start () {        //获取自身的ScrollRect组件        scrollRect = GetComponent<ScrollRect>();        contentTransform = transform.Find("ViewPort").Find("Content").GetComponent<RectTransform>();    }    // Update is called once per frame    void Update () {        //按A键添加子物体        if (Input.GetKeyDown(KeyCode.A))        {            Transform temp = Instantiate(itemTransform).transform;            temp.SetParent(contentTransform);            temp.localPosition = Vector3.zero;            temp.localRotation = Quaternion.identity;            temp.localScale = Vector3.one;        }    }}