Unity3d ugui 实现image代码换图

核心脚本代码

Image IMGE = transform.Find(“IMGE”).GetComponent();
Sprite sprite1 = Resources.Load(“Textrues/yutujing”, typeof(Sprite)) as Sprite;
IMGE.sprite = sprite1;

需要注意的是 Resources.Load 会读取Assets中Resources目录下的资源, Resources目录需要手动创建
或者

public Sprite[] sprites;

public Sprite[] sprite1;
void Update ()
{

    if (a>=200)
    {
        int Random1 = Random.Range(0,11);
        for (int i = 0; i < 11; i++)
        {
            if (Random1==i)
        {
            image1 = Rt.transform.GetChild(0).transform.GetChild(0).GetComponent<Image>();

            image2 = Rt.transform.GetChild(0).transform.GetChild(1).GetComponent<Image>();

            image1.sprite=sprites[Random1];

            image2.sprite=sprite1[Random1];

        }
        }
        
        Instantiate(Rt,new Vector3 ( Random.Range (-860,850), 1, Random.Range (-717,-500)), Quaternion.Euler(new Vector3(0,0,0)));

        a=1;
        
    }else
    {
        a=a+1;
    }

    Debug.Log(a);

}

}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码实现了自动轮播和手动滑动切换图片的功能: ```csharp using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ImageSlider : MonoBehaviour, IDragHandler, IEndDragHandler { public float autoPlayDelay = 3f; // 自动播放延迟时间 public float changeSpeed = 10f; // 切换速度 public bool autoPlay = true; // 是否自动播放 private ScrollRect scrollRect; private RectTransform content; private int currentIndex = 0; private float timer = 0f; void Start() { scrollRect = GetComponentInChildren<ScrollRect>(); content = scrollRect.content; currentIndex = 0; } void Update() { if (autoPlay) { timer += Time.deltaTime; if (timer > autoPlayDelay) { timer = 0f; currentIndex++; if (currentIndex >= content.childCount) { currentIndex = 0; } } } // 通过插值移动content的位置 Vector2 targetPos = new Vector2(currentIndex * scrollRect.viewport.rect.width, content.anchoredPosition.y); content.anchoredPosition = Vector2.Lerp(content.anchoredPosition, targetPos, Time.deltaTime * changeSpeed); } // 当用户结束拖拽时,计算当前应该显示哪张图片 public void OnEndDrag(PointerEventData eventData) { float posX = content.anchoredPosition.x; int index = Mathf.RoundToInt(posX / scrollRect.viewport.rect.width); currentIndex = index; } // 当用户拖拽时停止自动播放 public void OnDrag(PointerEventData eventData) { autoPlay = false; timer = 0f; } } ``` 这段代码中,我们实现了自动播放和手动滑动切换功能。autoPlayDelay表示自动播放的延迟时间,changeSpeed表示切换速度。在Update函数中,我们通过插值移动content的位置,从而实现图片的切换。在OnEndDrag函数中,我们计算当前应该显示哪张图片,然后将currentIndex设置为对应的索引。在OnDrag函数中,我们停止自动播放。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值