[Easy Getting Started] Two ways to use images to display 3D character status in real time on the UI

Method 1: Code implementation

Effect:

1: Build UI

Put the characters in the scene. Here I made a background image. You can choose it according to your preference.

Place an image in the lower left corner to display the character, named showRole;

Two: Hang a script <LockPlayer> on it

code show as below:

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

public class LockPlayer : MonoBehaviour
{
    public GameObject player;
    Camera camera;
    void Start()
    {
        //生成新相机,名字为cam
        GameObject cam = new GameObject("cam");
        camera = cam.AddComponent<Camera>();
        camera.clearFlags = CameraClearFlags.Color;
        //相机位置赋值
        camera.transform.position = player.transform.position + player.transform.forward + Vector3.up * 0.5f;
        //相机朝向
        camera.transform.LookAt(player.transform.position + Vector3.up * 0.5f);

        //纹理设置
        RenderTexture texture = new RenderTexture(256, 256,0);
        camera.targetTexture = texture;

        //材质设置
        Material material = new Material(Shader.Find("UI/Default"));
        material.mainTexture = texture;
        GetComponent<Image>().material = material;

    }

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

Three: Character dragging

Guess you like

Origin blog.csdn.net/m0_74022070/article/details/130106719