public void rebuildHandlerFromFunctionName() { MyContract.RequireFieldNotNull(callback_instance, "callback_instance"); MyContract.RequireFieldNotNull(handler_function_name, "handler_function_name"); Type callback_instance_type = callback_instance.GetType(); MethodInfo callback_method = callback_instance_type.GetMethod(handler_function_name); this.handler = delegate() { MyContract.RequireFieldNotNull( callback_method, "callback_method" ); MyContract.RequireArgumentNotNull( callback_instance, "callback_instance" ); //Debug.Log("Invoking delegate function " // + handler_function_name // + " | " // + callback_method.Name); try { callback_method.Invoke(callback_instance, null); } catch (Exception e) { Debug.Log("An exception happened when invoking a callback: " + e.Message); } }; }
public void Start() { MyContract.RequireFieldNotNull( OutputDisplayBox, "Output Display Box" ); }
public void SetValue(double newValue) { MyContract.RequireFieldNotNull( TextInput, "Text Input Component" ); MyContract.RequireFieldNotNull( SliderInput, "SliderInput Component" ); StoredValue = newValue; var e = FrameRateCapSet; lock (InitialisedLock) { if (Initialised && // short-circuit required OEM.shouldTriggerEvent(e)) { e.Invoke(newValue); } } // Updates are propagated between the two input components // in the editor // (via 3rd-party components - SliderUpdate & VariableTextBoxPrinter) }
/// <summary> /// /// </summary> /// <param name="stopHost"> /// Should be true if we need to stop the hosting aspects of the program /// </param> private void ExitNetworkGame(bool stopHost) { lock (FoundGameLock) { FoundGame = false; // I'm not sure if this is always safe to use, // as the documentation is very slim Debug.Log("Stopping game"); SetPlayerCamerasActive(false); if (stopHost) { GameStateManager GSM = GameStateManager.FindCurrentGameManager(); MyContract.RequireFieldNotNull(GSM, "Game State Manager"); NetworkManager.PlayerDisconnected -= GSM.OnPlayerDisconnect; NetworkManager.StopHost(); } if (NetworkDiscoverer.running) { // This stops both server broadcast and client listening NetworkDiscoverer.StopBroadcast(); } UIManager.SetPlayerConnectState( UIManager.PlayerConnectState.IDLE ); UIManager.EnterMainMenuRoot(); } }
protected override void GenerateSelectionLabels() { SelectionNames = new List <string>(); if (ObjectForMethodsToBeInvokedUpon != null || TypeForMethodsToBeInvokedUpon != null) { MyContract.RequireFieldNotNull(MemberSourceType, "MethodSourceType"); //Debug.Log("Got most derived type as " + MethodSourceType.ToString()); Members = new List <MemberInfo> (MemberSourceType .GetMethods(SelectionToShowFlags) ); ClassHasNoRelevantMembersToShow = Members.Count == 0; // Select guarantees the same ordering as the source // enumeration, so it's fine to use the index from // the selection_labels to index into the // listener_methods SelectionNames = Members .Select(x => x.Name) .ToList(); } else { //Debug.Log("Object is null, no SelectionLabels required"); } }
private void RpcPlayerShipSpawned (GameObject spawnedSpaceship) { MyContract.RequireArgumentNotNull( spawnedSpaceship, "Spawned Spaceship" ); Debug.Log("NPC: received RPC to receive spaceship"); playerShipSpawnedHandler(spawnedSpaceship); // This should be here, because if this ship controller // represents the local player, then we're guaranteed // to have witnessed all ship spawns directly through // this RPC; // therefore there's no need to check in the generic // case of playerShipSpawnedHandler which is also triggered // by the game-joining routines. // // N.B. This assumes that a player always initialises // their own ship spawning after they join the game. if (hasAuthority) { if (ShipController == null) { throw new InvalidOperationException( SHIP_CONTROLLER_NOT_SET_ERRMSG ); } ShipSpawnedHandler handler = LocalPlayerShipSpawned; if (oem.shouldTriggerEvent(handler)) { handler(ShipController); } } }
/// <summary> /// Sets both the state of all the graphics, /// and the simple bool state. /// </summary> /// <param name="on"></param> public void SetInitialToggleGraphicState(bool on) { MyContract.RequireFieldNotNull(ToggleButtonMover, "Toggle Button Mover"); //Debug.Log( // "Current toggle state: " // + CurrentToggleState.ToString() //); //Debug.Log("Setting toggle state " // + (on ? "on" : "off")); ensureInit(); if (on != CurrentToggleState) { foreach (EasyTween et in ToggleTweens) { et.OpenCloseObjectAnimation(); } foreach (EasyTween at in ToggleAntiTweens) { at.OpenCloseObjectAnimation(); } } ToggleButtonMover.setMoveState(on); CurrentToggleState = on; }
public void OnCameraDestroyed(CameraRoles role) { // If we have a good copy, use that if (CameraRegistry.Contains(role)) { Camera OurCamera = CameraRegistry[role]; if (OurCamera != null) { UIManager.ProvideCamera(OurCamera); } } // If we don't have a good copy, // try to find the prefab and build a new one foreach (Camera cam in CameraPrefabs) { CameraIdentifier ID = cam.GetComponent <CameraIdentifier>(); MyContract.RequireFieldNotNull(ID, "Camera Identifier"); CameraRoles PrefabRole = ID.Role; if (ID.Equals(role)) { List <Camera> ArgList = new List <Camera>(); ArgList.Add(cam); CameraRegistry.InitialiseAndRegisterGenericPrefabs(ArgList); Camera CreatedCamera = CameraRegistry[role]; UIManager.ProvideCamera(CreatedCamera); return; } } // If we don't have the prefab, we can't do anything }
RetrieveManager <ManagerType> (UIElements element) where ManagerType : Component { Type ExpectedManagerType = element.ManagerClass(); MyContract.RequireArgument( typeof(ManagerType) == ExpectedManagerType, "is expected type", "ManagerType: " + typeof(ManagerType).Name ); MyContract.RequireField ( this.Contains(element), "contains the element " + element.ToString(), "RegisteredObjects" ); ManagerType Manager = RegisteredObjects[(int)element].GetComponent <ManagerType>(); MyContract.RequireFieldNotNull( Manager, typeof(ManagerType).Name + " component of GameObject " + element.ToString() ); return(Manager); }
CreateNew (NetworkInstanceId controllerNetworkId) { MyContract.RequireArgumentNotNull( controllerNetworkId, "controllerNetworkId" ); GameObject PlayerControllerHost = NetworkServer.FindLocalObject(controllerNetworkId); MyContract.RequireArgumentNotNull( PlayerControllerHost, GameObjectNotPresentMessage ); NetworkedPlayerController PlayerController = PlayerControllerHost .GetComponent <NetworkedPlayerController>(); MyContract.RequireArgumentNotNull( PlayerController, NPCNotPresentMessage ); return(CreateNew(PlayerController)); }
CreateNew (NetworkedPlayerController controller) { MyContract.RequireArgumentNotNull( controller, "NetworkedPlayerController" ); PlayerIdentifier ExtantId = controller .gameObject .GetComponent <PlayerIdentifier>(); PlayerIdentifier NewId = ExtantId; if (ExtantId == null) { NewId = controller .gameObject .AddComponent <PlayerIdentifier>(); NewId.SetBackingController(controller); Debug.Log( "No existing PlayerIdentifier for " + NewId.ToString() + "\nCreating new PlayerIdentifier with net id " + NewId.netId ); } return(NewId); }
ActivateGameObjectsFromIntFlag (bool active, int bodiesToActivate) { if (bodiesToActivate == 0) // corresponds to none for flags { return; } List <int> FlaggedBodiesToActivate = new List <int>(); for (int CurrentFlagChecking = 1; CurrentFlagChecking <= bodiesToActivate; CurrentFlagChecking <<= 1) { if ((CurrentFlagChecking & bodiesToActivate) > 0) { FlaggedBodiesToActivate.Add(CurrentFlagChecking); } } MyContract.RequireArgument( FlaggedBodiesToActivate.Count > 0, "corresponds to at least one registered GameObject", "bodiesToActivate" ); ActivateGameObjects(active, FlaggedBodiesToActivate.ToArray()); }
public void CmdFirePhaser() { TimeSpan TimeElapsedSinceLastWeaponShot = DateTime.Now - TimeLastWeaponWasShot; if (TimeElapsedSinceLastWeaponShot > WeaponCD) { // Create the bolt locally GameObject Bolt = (GameObject)Instantiate( phaser_bolt_prefab, projectile_spawn_location.position, transform.rotation); Projectile BoltController = Bolt.GetComponent <Projectile>(); MyContract.RequireFieldNotNull(BoltController, "BoltController"); MyContract.RequireFieldNotNull(owner, "owner"); BoltController.shooter = owner; Bolt.GetComponent <Rigidbody>() .velocity = (PHASER_BOLT_FORCE * Bolt.transform.forward); // Spawn the bullet on the clients NetworkServer.Spawn(Bolt); // Set self-destruct timer Destroy(Bolt, 2.0f); TimeLastWeaponWasShot = DateTime.Now; } // else just ignore/drop this request }
/// <summary> /// Triggers the largest breakpoint in the input SortedList of input /// breakpoints, such that that breakpoint is larger than the given /// input value (either height or width) /// </summary> private void triggerLargestBreakpointBelow (SortedList <float, SortedList <float, ScreenBreakpointHandler> > breakpoints, float size) { MyContract.RequireArgument(breakpoints.Count > 0, "contains at least one entry", "breakpoints"); var trigger_enumerator = breakpoints.GetEnumerator(); while (trigger_enumerator.MoveNext() && trigger_enumerator.Current.Key > size) { float object_largest_triggered_breakpoint = trigger_enumerator.Current.Key; ScreenBreakpointHandler object_largest_triggered_function = null; var per_object_triggers = trigger_enumerator.Current.Value; if (per_object_triggers.Count <= 0) { throw new ArgumentException("one object has an entry without any breakpoints"); } var per_object_trigger_enumerator = per_object_triggers.GetEnumerator(); while (per_object_trigger_enumerator.MoveNext() && per_object_trigger_enumerator.Current.Key > size) { object_largest_triggered_breakpoint = per_object_trigger_enumerator.Current.Key; object_largest_triggered_function = per_object_trigger_enumerator.Current.Value; if (object_largest_triggered_function == null) { throw new ArgumentException( "one object has an entry with a null function " + "for breakpoint " + per_object_trigger_enumerator.Current.Key + "\n\n" + "Full breakpoints: " + printTriggers(breakpoints)); } } // trigger this object's largest breakpoint var current_object_breakpoints = trigger_enumerator.Current.Value; //Debug.Log("Invoking breakpoint at value " // + object_largest_triggered_breakpoint); //Debug.Log(printTriggers(breakpoints)); if (object_largest_triggered_function != null) { object_largest_triggered_function.Invoke(); } else { Debug.Log("WTF no function?"); } } }
public void BroadcastNewDateTime() { MyContract.RequireFieldNotNull(DateTimePicker, "DateTimePicker"); if (oem.shouldTriggerEvent(DateTimeSet)) { DateTimeSet(DateTimePicker.CurrentStoredValue); } }
public void DisplayFrameRateCapState(double initialValue) { MyContract.RequireFieldNotNull( FrameRateCapSetting, "Frame-rate Cap Setting" ); FrameRateCapSetting.DisplayValue(initialValue); }
public void SetZoom(float newZoom) { MyContract.RequireFieldNotNull( PlanetCameraController, "PlanetCameraController" ); DesiredCameraOrbitRadius = newZoom; ResetCameraOffset(); }
public void Start() { if (Slider == null) { Slider = GetComponent <Slider>(); } MyContract.RequireFieldNotNull(Slider, "Attached Slider component"); }
CmdSendScoreboardStateToUI() { MyContract.RequireFieldNotNull( ServerController, "ServerControler" ); ServerController.InitialiseScoreListener(this); }
public void UpdateScore(int newScore) { MyContract.RequireField(Initialised, "is true", "Initialised"); ScoreDisplay.text = newScore.ToString() + ScorePostfixString; this.score = newScore; }
GenericRegisterObject (Camera objectToRegister, bool objectIsAPrefab, InitialisationDelegate initialisationCallback, int Index) { Camera Instance; if (objectIsAPrefab) { GameObject Prefab = objectToRegister.gameObject; GameObject Obj = GameObject.Instantiate(Prefab); Instance = Obj.GetComponent <Camera>(); MyContract.RequireArgumentNotNull(Instance, "Camera Component"); } else { Instance = objectToRegister; Debug.Assert(Instance != null, "Provided object was null"); } if (initialisationCallback != null) { initialisationCallback(Instance, Index); } IGameObjectRegistryKeyComponent KeyComponent = Instance.GetComponent <IGameObjectRegistryKeyComponent>(); int element = KeyComponent.Key; //Debug.Log("Adding element " + element.ToString() + " to the dictionary."); if (RegisteredObjects.ContainsKey(element) && RetrieveObject(element) != null) { throw new InvalidOperationException( "Trying to register a second GameObject " + " with element identifier " + PrintKey(element) ); } else if (RegisteredObjects.ContainsKey(element) && RetrieveObject(element) == null) { // assume a deliberate replace intent RegisteredObjects[element] = Instance; } else { RegisteredObjects.Add(element, Instance); } if (PersistThroughScenes) { GameObject.DontDestroyOnLoad(Instance); GameObject.DontDestroyOnLoad(Instance.gameObject); } }
public string ToString() { if (PlayerID != null) { if (BackingController != null) { return(StandardIdentifier()); } else // can't use netid yet { // try to recover GameObject NPCHost; // The following section is disgusting, // but I can't tell why this is happening. // I only pull the value after // the local player controller is spawned // (in NetworkedPlayerController.OnStartServer) // so there's no reason why the gameobject // should be null/unready. // // It looks (to me) like Unity's networking tries to // instantiate this object with new rather than // with AddComponent, so it becomes "headless". // This is all undocumented behaviour, // so I'm just going to try and avoid dealing with it. try { NPCHost = gameObject; } catch (NullReferenceException nre) { Debug.LogWarning(NoGameObjectWarning); NPCHost = NetworkServer.FindLocalObject(PlayerID); if (NPCHost == null) { return(BackupIndentifier()); } } NetworkedPlayerController NPC = NPCHost .GetComponent <NetworkedPlayerController>(); MyContract.RequireFieldNotNull( NPC, "NetworkedPlayerController attached to the " + "local object corresponding to NetworkInstanceId " + PlayerID.ToString() ); BackingController = NPC; return(StandardIdentifier()); } } else { return("Null" + PrintInitStatus()); } }
public void SetSpaceshipClass(SpaceShipClass ssClass) { MyContract.RequireArgument( ssClass != SpaceShipClass.NONE, "is not NONE", "ssClass" ); CurrentSpaceshipClass = ssClass; }
/// <summary> /// This is expected to be called at game start, /// as the cameras could be used from the main menu /// </summary> public void InitialiseUICameras() { MyContract.RequireFieldNotNull(SSCManager, "Screen Size Change Manager"); CameraRegistry.PersistThroughScenes = true; CameraRegistry.KeyEnum = typeof(CameraRoles); CameraRegistry.InitialiseAndRegisterGenericPrefabs(CameraPrefabs); SSCManager.FixedUICamera = CameraRegistry[(int)CameraRoles.FixedUi]; //Debug.Log("Fixed UI Camera for the SSCManager has been set"); }
SetBackingController (NetworkedPlayerController controller) { MyContract.RequireArgumentNotNull( controller, "Networked Player Controller" ); BackingController = controller; PlayerID = controller.netId; }
public void BroadcastNewScale() { MyContract.RequireFieldNotNull(ScalePicker, "ScalePicker"); Debug.Log( "Broadcasting new " + ScalePicker.CurrentScaleType + " scale" ); ScalePicker.ScaleOption ScaleOption = ScalePicker.CurrentScaleType; switch (ScaleOption) { case ScalePicker.ScaleOption.Linear: if (oem.shouldTriggerEvent(PlanetLinearScaleSet) && ScalePicker.CurrentLinearScale != float.NaN && !float.IsInfinity(ScalePicker.CurrentLinearScale)) { PlanetLinearScaleSet( ScalePicker.CurrentLinearScale ); } break; case ScalePicker.ScaleOption.Logarithmic: if (oem.shouldTriggerEvent(PlanetLogarithmicScaleSet) && ScalePicker.CurrentLogBase != float.NaN && !float.IsInfinity(ScalePicker.CurrentLogBase) && ScalePicker.CurrentLogBase != 1 && ScalePicker.CurrentLogInnerMultiplier != float.NaN && !float.IsInfinity(ScalePicker.CurrentLogInnerMultiplier) && ScalePicker.CurrentLogOuterMultiplier != float.NaN && !float.IsInfinity(ScalePicker.CurrentLogOuterMultiplier)) { //Debug.Log( // "Passing on log values: " // + "log base " // + ScalePicker.CurrentLogBase // + ", inner multiplier " // + ScalePicker.CurrentLogInnerMultiplier // + ", outer multiplier" // + ScalePicker.CurrentLogOuterMultiplier //); PlanetLogarithmicScaleSet( ScalePicker.CurrentLogBase, ScalePicker.CurrentLogInnerMultiplier, ScalePicker.CurrentLogOuterMultiplier ); } break; default: throw new UnexpectedEnumValueException <ScalePicker.ScaleOption>(ScaleOption); } }
private void registerBreakpoints (SortedList <float, ScreenBreakpointHandler> object_breakpoints, object registrant, Dictionary <object, SortedList <float, ScreenBreakpointHandler> > object_registry, SortedList <float, SortedList <float, ScreenBreakpointHandler> > trigger_list) { MyContract.RequireArgumentNotNull(object_breakpoints, "object_breakpoints"); MyContract.RequireArgument(object_breakpoints.Count > 0, "contains at least one entry", "object_breakpoints"); var sorted_object_breakpoints = ensureTriggersAreInCorrectOrder(object_breakpoints); if (object_registry.ContainsKey(registrant) && object_registry[registrant] != null) { // Deduplication Debug.LogWarning(ADD_BREAKPOINT_EXISTING_OBJECT_WARN); var existing_breakpoints = object_registry[registrant]; var new_breakpoints = new SortedList <float, ScreenBreakpointHandler>( new FloatInverseOrderAllowDuplicatesComparer() ); foreach (var breakpoint in object_breakpoints.Concat(existing_breakpoints)) { MyContract.RequireArgumentNotNull(breakpoint.Value, "breakpoint callback"); new_breakpoints.Add(breakpoint.Key, breakpoint.Value); } var new_key = new_breakpoints.Keys.Max(); var existing_index = trigger_list.IndexOfValue(existing_breakpoints); // TODO: lock? We want this to be atomic object_registry.Remove(registrant); trigger_list.RemoveAt(existing_index); object_registry.Add(registrant, new_breakpoints); trigger_list.Add(new_key, new_breakpoints); //Debug.Log("Pulled old breakpoints: " // + printBreakpoints(existing_breakpoints)); //Debug.Log("Added new breakpoints: " // + printBreakpoints(object_breakpoints)); //Debug.Log("Created concatenated breakpoints: " // + printBreakpoints(new_breakpoints)); } else { Debug.Assert(sorted_object_breakpoints != null); Debug.Assert(sorted_object_breakpoints.Keys != null); //Debug.Log("sorted_object_breakpoints: " // + printBreakpoints(sorted_object_breakpoints)); float largest_breakpoint = sorted_object_breakpoints.Keys.Max(); object_registry.Add(registrant, object_breakpoints); trigger_list.Add(largest_breakpoint, object_breakpoints); //Debug.Log("Added breakpoints normally"); } }
/// <summary> /// Should be called when connecting to the server. /// This checks whether or not players have already spawned their ships, /// and if so it triggers the ship spawn event on this client /// to ensure that the program status is correct. /// /// N.B. Might break if the current spaceship is dead /// (but had been spawned). /// I think it should be fine though, I'm just not sure. /// TODO: test this /// </summary> public void initialiseShipSpawnStatus () { if (ShipSpawned) { MyContract.RequireFieldNotNull( CurrentSpaceship, "Current Spaceship" ); playerShipSpawnedHandler(CurrentSpaceship); } }
OnKillEvent (PlayerIdentifier hunter, PlayerIdentifier hunted) { Debug.Log(PrintPlayerScore()); MyContract.RequireField(PlayerScore.ContainsKey(hunter.PlayerID), "contains an entry for netid " + hunter.ToString(), "PlayerScore"); PlayerScore[hunter.PlayerID] += 1; ScoreUpdate(hunter, PlayerScore[hunter.PlayerID]); }
public IEnumerator LoadMainMenu() { MyContract.RequireFieldNotNull(LoadScreenCamera, "LoadScreenCamera"); MyContract.RequireFieldNotNull(LoadScreenCanvas, "LoadScreenCanvas"); Debug.Log("Main Menu Scene Loading"); yield return(new WaitUntil(() => ManagersHaveLoaded())); LoadScreenCanvas.SetActive(false); LoadScreenCamera.SetActive(false); gameObject.SetActive(false); }