简体   繁体   中英

Sprite object disappears from the game tab after repositioning with script

I'm new to Unity so this can be an amateur mistake. I'm trying to create a simple game that moves a simple sprite circle to a random position upon receiving touch input. the program works well in Scene tab, but the circle fully disappears in game tab and the connected remote device after receiving touch input.

Here's the script I have connected to my sprite circle Object :

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

public class Main : MonoBehaviour
{
    private Touch theTouch;
    private Camera cam;

    // Start is called before the first frame update
    void Start()
    {
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            theTouch = Input.GetTouch(0);
            if (theTouch.phase == TouchPhase.Ended)
            {
                MoveToRandomePosition();
            }
        }
    }

    // Random Movement
    void MoveToRandomePosition()
    {
        var position = cam.ScreenToWorldPoint(new Vector2(Random.Range(0, Screen.width), Random.Range(0, Screen.height)));
        transform.position = position;
    }
}

You may wanna check the Z coord of your camera and circle. If you're spawning it behind the camera, it wont render. You could do something like position.z = 0 if your cam pos is at the default -10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM