Home > database >  Sprite object disappears from the game tab after repositioning with script
Sprite object disappears from the game tab after repositioning with script

Time:11-13

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;
    }
}

CodePudding user response:

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.

  • Related