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;
}
Now, how does this function’s parameter catches players position, you may ask? And I shall grant you an answer! :D
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);
}
}
}
}
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.
Top comments (0)