A little confused

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

public class Play_area : MonoBehaviour
{

    [SerializeField] GameObject placeDefender;
    private void OnMouseDown()
    {
        spawnDefender(gotClick()); //使用spawnDefender時,會在呼叫gotClick指令獲得座標
    }
    private Vector2 gotClick()
    {
        Vector2 clickpos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 worldPos = Camera.main.ScreenToWorldPoint(clickpos);
        Vector2 gridPos = SnapToGrid(worldPos);
        return gridPos;
    }
    private Vector2 SnapToGrid(Vector2 rawworldPos) //建立一個座標名為SnapToGrid 
    {
        float newX = Mathf.RoundToInt(rawworldPos.x);
        float newY = Mathf.RoundToInt(rawworldPos.y);
        return new Vector2(newX, newY);
    }
    private void   spawnDefender(Vector2 worldPos) //使用時須給出座標
    {
        GameObject defender = Instantiate(placeDefender, worldPos, Quaternion.identity) as GameObject;
    }
}

I can’t understand some value in( )
like this part

============================================

 private Vector2 SnapToGrid(Vector2 rawworldPos)  <<   
    {
        float newX = Mathf.RoundToInt(rawworldPos.x);
        float newY = Mathf.RoundToInt(rawworldPos.y);
        return new Vector2(newX, newY);

===========================================
What is the meaning of “rawworldPos”?
i know Vector2 is mean coordinate
so “rawworldPos” is mean undefined coordinate? (like Variable in math?)
all part of this code is mean, get undefined X and Y ,then become to new Vector2?


private void   spawnDefender(Vector2 worldPos) //使用時須給出座標
    {
        GameObject defender = Instantiate(placeDefender, worldPos, Quaternion.identity) as GameObject;
    }

and this part. is “world Pos” same as a no coordinates identified?
if it’s no coordinates, how this function know where is the right place to use?

and the last question is when i should call the “Thing” in my function
and how i use it?

PS.sorry for poor english, i don’t know what to call it in ( ) :confused:

Hi,

Not undefined but you are right. It is a variable, a placeholder for an actual value.

There is a technique called method overloading. SnapToGrid is an overloaded method because a parameter is defined inside the parentheses. This means that the SnapToGrid method expects an object of type Vector2.

So does your spawnDefender method. It receives a Vector2 object. Then you can use the worldPos variable to use the data inside the method code block.

The variable inside the parentheses, (), is called parameter. When you call a method, you pass on arguments.

A simple example:

void DoSomething()
{
    Vector2 argument = Vector2.zero;
    spawnDefender(argument);
}

void spawnDefender (Vector2 parameter)
{
    // code
}

Does that make sense? :slight_smile:


See also:

as always,thank you Nina!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms