hwo to getComponent of a Scrip from a object that spawn in run time

hi, im building a game that when the game start, there is notting, then the enemy auto spawn, i click button to spawn ally unit to fight them, but both of the enemy and ally cant not get other scrip in order to acces the Take/Deal Dmg func, if i getcomponent at Start, there gonna be null because both of enemy and ally object are not there, i could put getcomponent in Update but people said it very bad. I use raycast in update for them to find each other and call Attacking Coroutine func; so if i put getcomponent in this raycast it would dash the getcomponent in update as well.
So is there another way for them to get each other component when each detect other has spawn in runtime without put GetComponent in Update.
thanks you
Here is the raycast find in update


here is the Attack Coroutine

For example, from your RaycastHit you can get all the information about the thing you hit that you want (This code assumes your script is called “Enemy”):

Enemy enemy = _hit.collider.GetComponent<Enemy>();

i try this before, but is this made the getcomponent always run in Update, cause my raycasthit is in update

Just use GetComponent in Update, there is nothing wrong with using it in moderation. People often say it is bad because it is much more efficient to cache the value, but with Raycasting it is usually much more of a hassle to cache the values of things you want to hit. As long as you’re not running into performance problems you don’t really have to change it.

well my game there is a point that need to spawn alot of object, now i still dont find any pref prob yet, and i want to ask about raycast, how to make the raycast hit multiple object, i want to make a unit that deal aoe attack, but right now my attack func with raycast only hit 1 object at a time, thanks you

I’d suggest using events. Every time an enemy spawns, you have a listener object (probably on the player) that gets the reference for you.

What you’re worried about here is a potential performance problem. But you need to solve your functionality problem before you worry about performance problems. Trust me this is not going to be a problem.

1 Like