Problem with touch controls and Instantiate()

Hello, I am new to Unity and I am trying to make an Android program.
When I touch the screen it would spawn a platform and when I move my finger while still touching the screen the platform would be moving, I don’t understand why this doesn’t work.

Here’s my scipt :

public class PlatformSpawn : MonoBehaviour
{
    public GameObject platform;

    void Start()
    {
       
    }

    void Update()
    {
        if(Input.touchCount>0)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                Vector2 firstPosition = Camera.main.ScreenToWorldPoint(touch.position);
                GameObject createdPlatform = Instantiate(platform, firstPosition, Quaternion.identity) as GameObject;

               
            }

            else if (touch.phase == TouchPhase.Moved)
                {
                    Vector2 movePosition = Camera.main.ScreenToWorldPoint(touch.position);
                    createdPlatform.transform.position = movePosition;
                }

        }
    }
}

Visual Studio tells me that createdPlatform doesn’t exist, could you please help me with that ? :slight_smile:

The variable createdPlatform is inaccessible in the TouchPhase.Moved block, because it’s a local variable inside the TouchPhase.Began if block.

Try making it a member variable like so:

public class PlatformSpawn : MonoBehaviour
{
    public GameObject platform;
    private GameObject createdPlatform;
    void Start()
    {
     
    }
    void Update()
    {
        if(Input.touchCount>0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                Vector2 firstPosition = Camera.main.ScreenToWorldPoint(touch.position);
                createdPlatform = Instantiate(platform, firstPosition, Quaternion.identity) as GameObject;
             
            }
            else if (touch.phase == TouchPhase.Moved)
                {
                    Vector2 movePosition = Camera.main.ScreenToWorldPoint(touch.position);
                    createdPlatform.transform.position = movePosition;
                }
        }
    }
}

Wow that was quick !!! It works now, thanks a lot !