Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Game Object appper in the Timerbutton

Discussion in 'General Discussion' started by subitdhakal1234, May 15, 2020.

  1. subitdhakal1234

    subitdhakal1234

    Joined:
    Nov 25, 2019
    Posts:
    15
    Hello , I am new to programming and i am stucked in one problem.
    When I touch in my timer button and after completion of timer .
    It instantiate the respective gameobject whereEver i touched in my screen. That's okay
    but when i Touch another timer UI button, the previous gameObject reappear in that touched Timer button..

    but after completion of second timer it instantiate the respective gameobject.where ever i touched in my screen
    and this problem re appear when i touch the first timer button
    please help me through this.

    Code of Timer Script
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class Timer : MonoBehaviour
    {
    [SerializeField] float duration=4f;
    public Image fillCircle;
    [SerializeField] Player playerPrefab;

    public void Start()
    {

    GetComponent<Image>().enabled = false;


    if (Input.touchCount >= 0)
    {
    GetComponent<Image>().enabled = true;
    for (int i = 0; i < Input.touchCount; i++)
    {

    Vector3 touchPosition = transform.TransformPoint(0, 0, 0);
    transform.position = touchPosition;
    fillCircle.fillAmount = 1f;
    StartCoroutine(StopWatch(duration));
    }
    }
    }

    IEnumerator StopWatch(float duration)
    {
    float startTime = Time.time;
    float time = duration;
    float value = 0;

    while (Time.time - startTime<duration)
    {
    time -= Time.deltaTime;
    value = time / duration;
    fillCircle.fillAmount = value;
    yield return null;
    }

    FindObjectOfType<PlayerSpawner>().PlayerSelected(playerPrefab);
    }
    }

    Code of GameObject Spawner

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

    public class PlayerSpawner : MonoBehaviour
    {
    Player player;


    void Update()
    {
    SpawnPlayer();
    }

    public void PlayerSelected(Player selectedPlayer)
    {
    player = selectedPlayer;
    }




    private void SpawnPlayer()
    {

    if (Input.touchCount > 0)
    {
    Touch touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Ended)
    {
    Vector2 touchPosition = Camera.main.ScreenToWorldPoint(new Vector2(touch.position.x, touch.position.y));
    Player newPlayer = Instantiate(player, touchPosition, Quaternion.identity) as Player;

    }
    }
    }
    }