I have some very basic multiplayer code working in a project.
The project allows two players to each have multiple ships in the scene at one time.
They can select one ship, move it around, select a different ship and move it, create a new ship, etc.
QUESTIONS:
How can I have my server keep track of all the objects that are created by all (two) of the players?
Is there an event on the server that is called each time Network.Instantiate(…) is called?
Once, I have a reference to the networked “ships” how will the server know what the current position of those game objects are?
The reason I want to track all the ships is so I can test when one of player 1’s ships is within range of one of player 2’s ships.
How about this. Create a script called ShipManager, attach it to the ship object and put this into it
import System.Collections.Generic;
static var ships : List.<GameObject> = new List.<GameObject>();
function OnNetworkInstantiate () {
// This is called when this object is created with Network.Instantiate
// First check to see that we are the server
if (Network.isServer) {
ships.Add(gameObject);
}
}
This will keep a list on the server of all the ship gameobjects. When you want to access this list from outside of this script simply use ShipManager.ships.
If you want to make two separate lists, one for each player, then just make two variables instead of one.
Whilst the above will keep track of the ships it may ot be the best way to achieve what you are after.
In this instance you are much better off putting trigger colliders on the ships out to the range you require, or even calling sphere overlap when you want to check the distance. Both of these will tell you what object they have hit, and you then have your information to hand to continue to perform your actions.
I find it is normally better to let the actions drive the results rather than checking for behaviour all the time. For example if you want to fire don’t get the firing object, the possible targets and then work out if one can fire at the other. Instead cast a ray from the firer and let it tell you who it hit.
I hope I am explaining this ok? What you are doing is not wrong, but there might be better ways to achieve what you are after, especially when your number of ships ramp up.