스크립트 파일 간의 데이터 전송

작성자

카테고리:

← 피드로
DEV Community · Giorgi Eliozashvili · 2026-07-19 개발(SW)
Cover image for Data transfer between script files

Giorgi Eliozashvili

I learned quite a lot today to compensate for the days that I had to drop. The most important piece of knowledge that I have gathered today is how to transfer data between script files. Let’s get to it:

So the problem was that I needed to catch the Player’s position when he set foot on a trigger that activates a small trap, which shoots hazardous balls at the Player’s coordinates.

I have two script files. One for a trigger object and the other for flying projectiles.

So at first, in a script file (file name: ProjectileTowardsPlayer.cs) for flying projectiles, I made a public function that receives the Player’s position when the trigger is activated (which happens in TriggerProjectiles.cs) and assigns its value to an already declared variable playerPosition.

public void PlayerPosAtTrigger(Vector3 playerPos)
    {
        playerPosition = playerPos;
    }

Enter fullscreen mode Exit fullscreen mode

Now, how does this function’s parameter catches players position, you may ask? And I shall grant you an answer! 😀

Here is my piece of code:

void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            for (int i = 0; i < projectiles.Length; i++)
            {
                if (projectiles[i] != null)
                {
                    var projectileScript = projectiles[i]
                        .GetComponent<ProjectileTowardsPlayer>();
projectileScript.PlayerPosAtTrigger(other.transform.position);

                    projectiles[i].SetActive(true);
                }
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode

Now, don’t think much about the logic of this. In short, it loops through projectiles, checks if the array value is null or not, and sets them active (because at the start, they are inactive). Now, projectileScript variable is where magic happens. When Player triggers the trap, we iterate through projectiles and set them active, and catch Player’s coordinates for TriggerProjectiles.cs using:

var projectileScript = projectiles[i].GetComponent<ProjectileTowardsPlayer>();

and then calling a PlayerPosAtTrigger() function and passing an argument to it

projectileScript.PlayerPosAtTrigger(other.transform.position);

so TriggerProjectiles.cs will know Player’s coordinates, and trap will shoot at the correct location.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다