Hello,
So after literally days of troubleshooting this issue, I’m giving up and want to try getting some help here.
Unfortunately, I searched this error here and didn’t really get an answer for my issue.
I’ll try to put as much context as I can to avoid that you miss important information to help me:
Scenes setup:
«A»: Main Menu scene
«B»: Lobby Scene
There is then a play scene but this doesn’t matter anymore as the error only comes in the lobby scene because of the first Player models instantiation.
In Scene «A», Player 1 through the UI can create a room. there are no Photon involved here, clicking on the Create room button setup a bunch of variables and Load Scene «B»
In Scene «B», Player 1 through a lobby script, creates the Room. Then in the network manager it uses the photon Callback
public override void OnJoinedRoom()
In there it checks if we are Master Client, if yes we setup some room props and trigger then the instantiation of the Player Prefab using of course:
PhotonNetwork.Instantiate()
From the point in time, everything works perfectly fine
At this point, Player 2 decides to join the game. Same, Scene «A», only UI without any photon magic in this scene, it just save the room name variable and Load Scene «B» (I tried with PhotonNetwork.LoadLevel(«sceneName») too)
In that scene Player 2 Join the room and that’s where the disaster starts!
As soon as we join the room I get the error message. I know the error is longer that usual but I added some stuff in the Debug.Log to try to pin point what RPC was the cause from where to who etc.
ERROR You have missing MonoBehaviours on your gameobjects!|| And that is this RPC: UpdateCharacter|| Sender is: #01 'Necka' || Receiver might be: [1001] Photon_Player_Base_V1 - Remote [MasterClient] UnityEngine.Debug:LogError (object) Photon.Pun.PhotonNetwork:ExecuteRpc (ExitGames.Client.Photon.Hashtable,Photon.Realtime.Player) (at Assets/____Assets/__Asset Store/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:473) Photon.Pun.PhotonNetwork:OnEvent (ExitGames.Client.Photon.EventData) (at Assets/____Assets/__Asset Store/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:2210) Photon.Realtime.LoadBalancingClient:OnEvent (ExitGames.Client.Photon.EventData) (at Assets/____Assets/__Asset Store/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:3336) ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:891) ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:558) ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1837) Photon.Pun.PhotonHandler:Dispatch () (at Assets/____Assets/__Asset Store/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:223) Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/____Assets/__Asset Store/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:149)
As previously stated, here Player 2 through the OnJoinedRoom() Photon callback check if were are master and as it’s not, it just go straight to instantiating his own Player Prefab.
The error happens before the instantiation of the Prefab. And that’s where I understand why. The RPC is supposed to be received from a component that’s on the Player Prefab. I didn’t instantiate it yet, so it can’t receive it.
The fun part of course is that this error is triggered only once and that absolutely everything is working fine after the instantiation, there are no problems at all. Everything is synced etc. So you could say «ok just ignore the error and move on» But I have OCD with those red lines. It doesn’t look professional in the Player Log either and I’m not accepting errors in my project, simple as that
More info:
The RPC is sent like this from this Character script located on the Player Prefab:
public override void OnPlayerEnteredRoom(Player player) { if (photonView.IsMine && gameObject.activeSelf) { var lcm = Locomotion; photonView.RPC(RPC_CHARACTER, player, transform.position, lcm.canUseNavigationMesh, currentControls, new Vector2(Locomotion.runSpeed, currentAngularSpeed), currentGravity, currentJump, (int)lcm.faceDirection, syncAttachments ? SerializeAttachments() : emptyHashtable); } }
The RPC is received as:
[PunRPC] private void UpdateCharacter(Vector3 position, bool canUseNavigationMesh, Vector2 controls, Vector2 speed, Vector2 gravity, Vector2 jump, int faceDirection, Hashtable attachments) { Some code }
At that point I have no clue on how to troubleshoot this issue anymore. Do be fully transparent, I’m using a Unity module which lift the heavy weight on the Photon side and allow me to do most things in a visual scripting way. But I do know my way around code but that’s also the reason why I’m not sharing too much details on code here, but can answer any questions of course!
Thank you in advance for your support, I hope my post isn’t too complicated to understand
Содержание
- ERROR You have missing MonoBehaviours on your gameobjects!
- Damage dealing scripts
- Comments
- Error you have missing monobehaviours on your gameobjects
- Error you have missing monobehaviours on your gameobjects
- MonoBehaviour
- Success!
- Submission failed
- Description
- Properties
- Public Methods
- Static Methods
- Messages
- Inherited Members
- Properties
- Public Methods
- Static Methods
- Operators
ERROR You have missing MonoBehaviours on your gameobjects!
Hello,
So after literally days of troubleshooting this issue, I’m giving up and want to try getting some help here.
Unfortunately, I searched this error here and didn’t really get an answer for my issue.
I’ll try to put as much context as I can to avoid that you miss important information to help me:
Scenes setup:
«A»: Main Menu scene
«B»: Lobby Scene
There is then a play scene but this doesn’t matter anymore as the error only comes in the lobby scene because of the first Player models instantiation.
In Scene «A», Player 1 through the UI can create a room. there are no Photon involved here, clicking on the Create room button setup a bunch of variables and Load Scene «B»
In Scene «B», Player 1 through a lobby script, creates the Room. Then in the network manager it uses the photon Callback
In there it checks if we are Master Client, if yes we setup some room props and trigger then the instantiation of the Player Prefab using of course:
From the point in time, everything works perfectly fine
At this point, Player 2 decides to join the game. Same, Scene «A», only UI without any photon magic in this scene, it just save the room name variable and Load Scene «B» (I tried with PhotonNetwork.LoadLevel(«sceneName») too)
In that scene Player 2 Join the room and that’s where the disaster starts!
As soon as we join the room I get the error message. I know the error is longer that usual but I added some stuff in the Debug.Log to try to pin point what RPC was the cause from where to who etc.
As previously stated, here Player 2 through the OnJoinedRoom() Photon callback check if were are master and as it’s not, it just go straight to instantiating his own Player Prefab.
The error happens before the instantiation of the Prefab. And that’s where I understand why. The RPC is supposed to be received from a component that’s on the Player Prefab. I didn’t instantiate it yet, so it can’t receive it.
The fun part of course is that this error is triggered only once and that absolutely everything is working fine after the instantiation, there are no problems at all. Everything is synced etc. So you could say «ok just ignore the error and move on» But I have OCD with those red lines. It doesn’t look professional in the Player Log either and I’m not accepting errors in my project, simple as that
The RPC is sent like this from this Character script located on the Player Prefab:
The RPC is received as:
At that point I have no clue on how to troubleshoot this issue anymore. Do be fully transparent, I’m using a Unity module which lift the heavy weight on the Photon side and allow me to do most things in a visual scripting way. But I do know my way around code but that’s also the reason why I’m not sharing too much details on code here, but can answer any questions of course!
Thank you in advance for your support, I hope my post isn’t too complicated to understand
Источник
Damage dealing scripts
Okay i posted this question a whiles back and didn’t really get the help i needed, i’m trying to set up third person combat but i can’t seem to deal damage to the other player i even purchased the M2H guides and tried using the fps example i’ll show how far I’ve got then i’ll explain more
[code2=csharp]public int damage = 50;
public int range = 10;
void MeleeCombat()
<
Vector3 direction = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
// Did we hit anything?
if (Physics.Raycast(transform.position, direction * 2, out hit))
<
hit.collider.SendMessage(«ApplyDamage», damage, SendMessageOptions.DontRequireReceiver);
>
// Update is called once per frame
void Update () <
Vector3 direction = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position,direction * 2,Color.blue);
if (Input.GetButtonDown(«Fire1»))
<
MeleeCombat();
>
>
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
<
if(stream.isWriting)
<
>
>[/code2]
This is my damage dealing script and is attached to an empty gameobject on the player prefab
[code2=csharp]public int hp = 100;
void ApplyDamage(int Damage)
<
hp -= (int)Damage;
if (hp 0
Maybe the HP setting doesn’t work, because you have those errors.
Let’s fix them first.
«You have missing MonoBehaviours on your gameobjects!»
I had to look this up but I can’t yet explain it. With photonNetview.GetComponents (), we get all MonoBehaviours on the gameObject that we target. For some reason, this is null, causing the output.
Usually, this doesn’t happen. Maybe you remove a component from your GameObjects or do something similar with it.
Find out which GameObject this is and check if you have scripts on that. You can’t call RPCs on GameObjects which don’t have scripts (which implement the RPC).
PhotonView with ID 1001 has 2 methods «setHP» that takes 1 argument(s): Int32. Should be just one?
This error sounds like you didn’t copy all of the relevant code into your post. You seem to have 2 implementations of setHP(someParameter).
Try to find the duplicate and get rid of it. You can use multiple names for RPCs to do different things.
Источник
Error you have missing monobehaviours on your gameobjects
How to reproduce:
1. Open the attached «Repro.zip» project
2. Open the Main scene
3. Enter Play mode
4. Observe the Console errors
5. In Hierarchy, select «GameObject» prefab and remove the reference to non-MonoBehaviourscript
6. Enter the Play mode again
7. Observe the same Console errors.
Expected behavior: Along with (or instead of) the below-mentioned errors, the user is informed about the class that is not derived from MonoBehaviour or ScriptableObject.
Actual behavior: The error message that informs about the class that is not derived from MonoBehaviour or ScriptableObject is shown only when entering Play mode in the scene that contains a GameObject with such non-MonoBehaviour component.
Reproducible with — 2017.3.0a1, 2017.4.19f1, 2018.3.3f1, 2019.1.0b1, 2019.2.0a3
Errors thrown:
— «‘ ‘ is missing the class attribute ‘ExtensionOfNativeClass’!» (does not appear in 2017.4)
— «GameObject (named ‘ ‘) references runtime script in scene file. Fixing!»
Workaround: Manually remove non-MonoBehavour script components from GameObjects and Prefabs.
Resolution Note (2018.3.X):
Until the reference to the script is removed from the prefab this error will continue to pop up. This is because entering play mode works by loading the scene and the prefab (which causes the error), then merge the prefab into scene during which the component is removed. So removing it in the scene is not enough the reference also needs to be removed from the prefab.
Источник
Error you have missing monobehaviours on your gameobjects
How to reproduce:
1. Open the attached «Repro.zip» project
2. Open the Main scene
3. Enter Play mode
4. Observe the Console errors
5. In Hierarchy, select «GameObject» prefab and remove the reference to non-MonoBehaviourscript
6. Enter the Play mode again
7. Observe the same Console errors.
Expected behavior: Along with (or instead of) the below-mentioned errors, the user is informed about the class that is not derived from MonoBehaviour or ScriptableObject.
Actual behavior: The error message that informs about the class that is not derived from MonoBehaviour or ScriptableObject is shown only when entering Play mode in the scene that contains a GameObject with such non-MonoBehaviour component.
Reproducible with — 2017.3.0a1, 2017.4.19f1, 2018.3.3f1, 2019.1.0b1, 2019.2.0a3
Errors thrown:
— «‘ ‘ is missing the class attribute ‘ExtensionOfNativeClass’!» (does not appear in 2017.4)
— «GameObject (named ‘ ‘) references runtime script in scene file. Fixing!»
Workaround: Manually remove non-MonoBehavour script components from GameObjects and Prefabs.
Resolution Note (2018.3.X):
Until the reference to the script is removed from the prefab this error will continue to pop up. This is because entering play mode works by loading the scene and the prefab (which causes the error), then merge the prefab into scene during which the component is removed. So removing it in the scene is not enough the reference also needs to be removed from the prefab.
Источник
MonoBehaviour
class in UnityEngine
Success!
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
Submission failed
For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
Description
MonoBehaviour is the base class from which every Unity script derives.
When you use C#, you must explicitly derive from MonoBehaviour.
This class doesn’t support the null-conditional operator (?.) and the null-coalescing operator (??).
For code samples, see the individual MonoBehaviour methods.
Note: There is a checkbox for enabling or disabling MonoBehaviour in the Unity Editor. It disables functions when unticked. If none of these functions are present in the script, the Unity Editor does not display the checkbox. The functions are:
See Also: The Deactivating GameObjects page in the manual.
Properties
runInEditMode | Allow a specific instance of a MonoBehaviour to run in edit mode (only available in the editor). |
useGUILayout | Disabling this lets you skip the GUI layout phase. |
Public Methods
CancelInvoke | Cancels all Invoke calls on this MonoBehaviour. |
Invoke | Invokes the method methodName in time seconds. |
InvokeRepeating | Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds. |
IsInvoking | Is any invoke on methodName pending? |
StartCoroutine | Starts a Coroutine. |
StopAllCoroutines | Stops all coroutines running on this behaviour. |
StopCoroutine | Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour. |
Static Methods
Logs message to the Unity Console (identical to Debug.Log). |
Messages
Awake | Awake is called when the script instance is being loaded. |
FixedUpdate | Frame-rate independent MonoBehaviour.FixedUpdate message for physics calculations. |
LateUpdate | LateUpdate is called every frame, if the Behaviour is enabled. |
OnAnimatorIK | Callback for setting up animation IK (inverse kinematics). |
OnAnimatorMove | Callback for processing animation movements for modifying root motion. |
OnApplicationFocus | Sent to all GameObjects when the player gets or loses focus. |
OnApplicationPause | Sent to all GameObjects when the application pauses. |
OnApplicationQuit | Sent to all GameObjects before the application quits. |
OnAudioFilterRead | If OnAudioFilterRead is implemented, Unity will insert a custom filter into the audio DSP chain. |
OnBecameInvisible | OnBecameInvisible is called when the renderer is no longer visible by any camera. |
OnBecameVisible | OnBecameVisible is called when the renderer became visible by any camera. |
OnCollisionEnter | OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider. |
OnCollisionEnter2D | Sent when an incoming collider makes contact with this object’s collider (2D physics only). |
OnCollisionExit | OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider. |
OnCollisionExit2D | Sent when a collider on another object stops touching this object’s collider (2D physics only). |
OnCollisionStay | OnCollisionStay is called once per frame for every Collider or Rigidbody that touches another Collider or Rigidbody. |
OnCollisionStay2D | Sent each frame where a collider on another object is touching this object’s collider (2D physics only). |
OnConnectedToServer | Called on the client when you have successfully connected to a server. |
OnControllerColliderHit | OnControllerColliderHit is called when the controller hits a collider while performing a Move. |
OnDestroy | Destroying the attached Behaviour will result in the game or Scene receiving OnDestroy. |
OnDisable | This function is called when the behaviour becomes disabled. |
OnDisconnectedFromServer | Called on the client when the connection was lost or you disconnected from the server. |
OnDrawGizmos | Implement OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn. |
OnDrawGizmosSelected | Implement OnDrawGizmosSelected to draw a gizmo if the object is selected. |
OnEnable | This function is called when the object becomes enabled and active. |
OnFailedToConnect | Called on the client when a connection attempt fails for some reason. |
OnFailedToConnectToMasterServer | Called on clients or servers when there is a problem connecting to the MasterServer. |
OnGUI | OnGUI is called for rendering and handling GUI events. |
OnJointBreak | Called when a joint attached to the same game object broke. |
OnJointBreak2D | Called when a Joint2D attached to the same game object breaks. |
OnMasterServerEvent | Called on clients or servers when reporting events from the MasterServer. |
OnMouseDown | OnMouseDown is called when the user has pressed the mouse button while over the Collider. |
OnMouseDrag | OnMouseDrag is called when the user has clicked on a Collider and is still holding down the mouse. |
OnMouseEnter | Called when the mouse enters the Collider. |
OnMouseExit | Called when the mouse is not any longer over the Collider. |
OnMouseOver | Called every frame while the mouse is over the Collider. |
OnMouseUp | OnMouseUp is called when the user has released the mouse button. |
OnMouseUpAsButton | OnMouseUpAsButton is only called when the mouse is released over the same Collider as it was pressed. |
OnNetworkInstantiate | Called on objects which have been network instantiated with Network.Instantiate. |
OnParticleCollision | OnParticleCollision is called when a particle hits a Collider. |
OnParticleSystemStopped | OnParticleSystemStopped is called when all particles in the system have died, and no new particles will be born. New particles cease to be created either after Stop is called, or when the duration property of a non-looping system has been exceeded. |
OnParticleTrigger | OnParticleTrigger is called when any particles in a Particle System meet the conditions in the trigger module. |
OnParticleUpdateJobScheduled | OnParticleUpdateJobScheduled is called when a Particle System’s built-in update job has been scheduled. |
OnPlayerConnected | Called on the server whenever a new player has successfully connected. |
OnPlayerDisconnected | Called on the server whenever a player disconnected from the server. |
OnPostRender | Event function that Unity calls after a Camera renders the scene. |
OnPreCull | Event function that Unity calls before a Camera culls the scene. |
OnPreRender | Event function that Unity calls before a Camera renders the scene. |
OnRenderImage | Event function that Unity calls after a Camera has finished rendering, that allows you to modify the Camera’s final image. |
OnRenderObject | OnRenderObject is called after camera has rendered the Scene. |
OnSerializeNetworkView | Used to customize synchronization of variables in a script watched by a network view. |
OnServerInitialized | Called on the server whenever a Network.InitializeServer was invoked and has completed. |
OnTransformChildrenChanged | This function is called when the list of children of the transform of the GameObject has changed. |
OnTransformParentChanged | This function is called when a direct or indirect parent of the transform of the GameObject has changed. |
OnTriggerEnter | When a GameObject collides with another GameObject, Unity calls OnTriggerEnter. |
OnTriggerEnter2D | Sent when another object enters a trigger collider attached to this object (2D physics only). |
OnTriggerExit | OnTriggerExit is called when the Collider other has stopped touching the trigger. |
OnTriggerExit2D | Sent when another object leaves a trigger collider attached to this object (2D physics only). |
OnTriggerStay | OnTriggerStay is called once per physics update for every Collider other that is touching the trigger. |
OnTriggerStay2D | Sent each frame where another object is within a trigger collider attached to this object (2D physics only). |
OnValidate | Editor-only function that Unity calls when the script is loaded or a value changes in the Inspector. |
OnWillRenderObject | OnWillRenderObject is called for each camera if the object is visible and not a UI element. |
Reset | Reset to default values. |
Start | Start is called on the frame when a script is enabled just before any of the Update methods are called the first time. |
Update | Update is called every frame, if the MonoBehaviour is enabled. |
Inherited Members
Properties
enabled | Enabled Behaviours are Updated, disabled Behaviours are not. |
isActiveAndEnabled | Reports whether a GameObject and its associated Behaviour is active and enabled. |
gameObject | The game object this component is attached to. A component is always attached to a game object. |
tag | The tag of this game object. |
transform | The Transform attached to this GameObject. |
hideFlags | Should the object be hidden, saved with the Scene or modifiable by the user? |
name | The name of the object. |
Public Methods
BroadcastMessage | Calls the method named methodName on every MonoBehaviour in this game object or any of its children. |
CompareTag | Checks the GameObject’s tag against the defined tag. |
GetComponent | Returns the component of type if the GameObject has one attached. |
GetComponentInChildren | Returns the Component of type in the GameObject or any of its children using depth first search. |
GetComponentInParent | Returns the Component of type in the GameObject or any of its parents. |
GetComponents | Returns all components of Type type in the GameObject. |
GetComponentsInChildren | Returns all components of Type type in the GameObject or any of its children using depth first search. Works recursively. |
GetComponentsInParent | Returns all components of Type type in the GameObject or any of its parents. |
SendMessage | Calls the method named methodName on every MonoBehaviour in this game object. |
SendMessageUpwards | Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour. |
TryGetComponent | Gets the component of the specified type, if it exists. |
GetInstanceID | Gets the instance ID of the object. |
ToString | Returns the name of the object. |
Static Methods
Destroy | Removes a GameObject, component or asset. |
DestroyImmediate | Destroys the object obj immediately. You are strongly recommended to use Destroy instead. |
DontDestroyOnLoad | Do not destroy the target Object when loading a new Scene. |
FindObjectOfType | Returns the first active loaded object of Type type. |
FindObjectsOfType | Gets a list of all loaded objects of Type type. |
Instantiate | Clones the object original and returns the clone. |
Operators
bool | Does the object exist? |
operator != | Compares if two objects refer to a different object. |
operator == | Compares two object references to see if they refer to the same object. |
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright ©2023 Unity Technologies. Publication Date: 2023-01-06.
Источник
Local folder or tarball paths
This section provides information on the following issues:
Type of error: | Error message: |
---|---|
General startup issues | — Error messages in the Package Manager window — Package Manager missing or window doesn’t open — Problems after upgrading Unity to new version — Resetting your project’s package configuration |
Package installation issues | — Package installation fails — Packages not recognized — Unable to add package from Git URL |
Problems installing git dependencies | — No ‘git’ executable was found — git-lfs: command not found — Repository not found — Could not read Username: terminal prompts disabled — Can’t update Git version |
Asset StoreA growing library of free and commercial assets created by Unity and members of the community. Offers a wide variety of assets, from textures, models and animations to whole project examples, tutorials and Editor extensions. More info See in Glossary packages (My Assets) |
— ‘Failed to parse Http response’ in My Assets context |
Scoped registries | — Missing ‘My Registries’ in the Package Manager window |
Issues when building packages | — Missing MonoBehaviour errors — Loading error for hostfxr.dll on Windows |
You can also run the Unity Package Manager Diagnostics tool if you are experiencing problems that might be network-related. For more information, see Diagnose network issues.
Error messages in the Package Manager window
The Package Manager displays error indicators in the Package Manager window when it encounters problems.
System-wide issues
-
Network connection issues
Error messages appear in the status bar when the Package Manager has detected an issue that isn’t related to a specific package. For example, if the Package Manager can’t access the package registry server, it displays this message in the status bar:
Network error message -
Error refreshing assets (or Error refreshing packages)
If your network can’t reach the package registry server, it’s probably because there is a connection problem with the network. When you or your system administrator diagnose and fix the network error, the status bar clears.
If your network connection is working, but you aren’t signed into your Unity account, the Package Manager doesn’t display any Asset Store packages. When you try to use the My Assets context, the Package Manager displays an error in the status bar:
Logged out of Unity account Click the Sign in button inside the list view to sign into your Unity account through the Unity Hub.
Package-specific issues
-
If a specific package has a problem when loading or installing (for example, when determining which package versions to load), the error icon () appears in the package list next to the compromised package (A). To find out what the problem is, open the compromised package’s details view to see the detailed error message (B):
Dependency error message
Package Manager missing or window doesn’t open
The Package Manager window might get moved offscreen or hidden by another window. When this happens, it looks like the Package Manager window failed to open. In this case, you can try to reset the window layout (Window > Layouts > Default) and reopen the Package Manager window again.
If the Package Manager window still doesn’t appear, check your Unity Console windowA Unity Editor window that shows errors, warnings and other messages generated by Unity, or your own scripts. More info
See in Glossary:
Failed to resolve packages: The file [<project-path>/Packages/manifest.json] is not valid JSON:
Unexpected token '}' at 44:1
}
This error message indicates that your manifest.json
file is malformed. It also tells you the line number where the Package Manager failed to parse the file, so you can fix the JSON. There are a number of online validators that you can use to try to correct the problem. Once you save the corrected file, Unity reloads the Package Manager window.
If you upgraded from an early version of the Unity Editor, there may be other problems with your package manifestEach package has a manifest, which provides information about the package to the Package Manager. The manifest contains information such as the name of the package, its version, a description for users, dependencies on other packages (if any), and other details. More info
See in Glossary file:
-
As of 2019.3, your
manifest.json
file should not contain any references to the com.unity.package-manager-ui package. You can either reset your project’s package configuration or remove the following line from the manifest’s dependencies list:"com.unity.package-manager-ui": "2.1.1",
-
Check to see if your project manifestEach Unity project has a project manifest, which acts as an entry point for the Package Manager. This file must be available in the
<project>/Packages
directory. The Package Manager uses it to configure many things, including a list of dependencies for that project, as well as any package repository to query for packages. More info
See in Glossary uses “exclude” as a package version. This is an obsolete value for the dependencies property. If you find any lines like these, remove the entire line. Package Manager only installs packages that are explicitly included as a dependency in your project, so once you remove that entry, Package Manager ignores the package and doesn’t install it.
If the Package Manager still fails to load, follow the procedures under Packages not recognized and Resetting your project’s package configuration.
Problems after upgrading Unity to new version
When you upgrade a project to a newer Unity version, the Package Manager automatically updates incompatible packages to newer compatible versions. However, if your package doesn’t compile, the Package Manager displays error messages in the Console.
To correct these messages, read the error messages and fix any problems you can. For example, a package might be missing a dependency on another package or version. In that case, you can try and install the package yourself.
You can also try the following sequence of solutions until you find something that works:
- Back up and then delete the
Packages
folder under your project. - Back up and then delete the package sources in your project’s
Packages
folder, leaving only themanifest.json
file. Then try to reload the project. - Create a new empty project. If the Package Manager window loads successfully, replace the
Library/PackageCache/com.unity.package-manager-ui@<version>
folder in the failing project with the same folder from the newly created project. - As a last resort, you can reset your project to the default packageUnity automatically pre-installs a select number of default packages (for example, the Analytics Library, Unity Timeline, etc.) when you create a new project. This differs from a bundled package because you don’t need to install it and it differs from a built-in package because it extends Unity’s features rather than being able to enable or disable them.
See in Glossary configuration and add back packages one at a time until it works.
Resetting your project’s package configuration
If a project has too many package issues, you can reset your project back to the default package configuration for the Editor’s version of Unity. This operation resets all packages in your project. This might not fix the source of the problem, but it can help you figure out what the problem is.
Note: You can’t undo resetting your package configuration, so make sure you back up the manifest.json
file first or make sure your project is under source control. You can also take extra precautions by cloning your project and testing out the operation on the clone before proceeding.
To return to the default package configuration, select Reset Packages to defaults from the Help menu.
Resetting a clone of your project
You can also test the return to the default packages before you perform the final change:
-
Clone your project by copy-pasting your project folder and renaming it so that it is easy to find (for example, if your project is called
MyProject
then you could use something likeclone_MyProject
). -
Load your newly cloned project.
-
From the Help menu, select Reset Packages to defaults.
Depending on the size of your project, this might take a few minutes.
-
Check that it successfully reset the packages. If so, you can perform the operation safely on the original project.
Package installation fails
If you are trying to install a new package from the registry and it is not working, it might be due to permission problems.
You must have full permissions on the cache folder:
- Windows:
C:UsersyournameAppDataLocalUnitycache
- macOS:
~/Library/Unity/cache
- Linux:
~/.config/unity3d/cache
It might be a problem with the network. Check your firewall and proxy settings.
Sometimes institutional environments, such as schools, government offices, or network-protected workplaces set up proxy servers to control traffic between the network and the Internet, and use their own server certificates which are not recognized by Unity or the Package Manager. Talk to your network administrator.
Packages not recognized
If you see a lot of compilation errors, this might indicate that Unity is not recognizing the packages in your existing project. In this case, you might be missing a .NET component.
For Windows:
- Download and install Visual Studio 2017 version 15.9.0 or higher with the .NET Core cross-platform development workload selected under Other Toolsets.
- Download and install the .NET SDK v2.2.101 component.
For MacOS:
-
Download and install the .NET SDK v2.2.101 component.
-
Install any recommended updates in Visual Studio
-
Use homebrew to brew and install mono:
brew update brew install mono # optional brew upgrade mono
-
If necessary, delete the
Library/obj/temp
folder under your project and restart Unity. -
If you are still experiencing difficulties, try rebooting your computer as well.
Unable to add package from Git URL
See Repository not found.
No ‘git’ executable was found
If you try to install a package from a git URL, a message similar to this appears:
Cannot perform upm operation: Unable to add package
[https://github.example.com/myuser/myrepository.git]:
No 'git' executable was found. Please install Git on your system and restart Unity [NotFound]
UnityEditor.EditorApplication:Internal_CallUpdateFunctions()
git-lfs: command not found
If you are trying to download a package that uses Git LFS (Large File Storage), you might see this error message:
Error when executing git command. git-lfs filter-process: command not found.
This indicates that Git LFS is probably not installed on your machine. To make sure, you could test it on the command line:
git lfs --version
If you see something like this, Git LFS is installed:
git-lfs/2.8.0 (GitHub; darwin amd64; go 1.12.7)
Otherwise, you can install it by following the Bitbucket GitHub instructions.
Repository not found
If you specify a location that does not exist, a message similar to this one appears in the Unity Console:
Cannot perform upm operation: Unable to add package [https://mycompany.github.com/gitproject/com.mycompany.mypackage.git]:
Error when executing git command. fatal: repository 'https://mycompany.github.com/gitproject/com.mycompany.mypackage.git/' not found
[NotFound]
UnityEditor.EditorApplication:Internal_CallUpdateFunctions() (at /Users/builduser/buildslave/unity/build/Editor/Mono/EditorApplication.cs:310)
Check your spelling. To make sure you are using the correct URL, go to the repository’s page and copy the URL from the Clone button:
Click the button to the right of the URL on GitHub (A) or GitLab (B) to copy the URL to your clipboard.
If the location of the repository is correct, there may be another problem with the URL:
- If you are targeting a specific revision, make sure your revision comes last. For example:
https://github.example.com/myuser/myrepository1.git#revision
- If you are targeting a revision and the package is not at the root, make sure the
path
query parameter precedes the revision anchor. For example:https://github.example.com/myuser/myrepository.git?path=/example/folder#v1.2.3
Could not read Username: terminal prompts disabled
If you are trying to install a package from a private repository that requires authentication, a message similar to this one appears in the Unity Console:
Cannot perform upm operation: Unable to add package [https://mycompany.github.com/gitproject/com.mycompany.mypackage.git]:
Error when executing git command. fatal: could not read Username for 'https://mycompany.github.com': terminal prompts disabled
[NotFound]
UnityEditor.EditorApplication:Internal_CallUpdateFunctions() (at /Users/builduser/buildslave/unity/build/Editor/Mono/EditorApplication.cs:310)
This message is likely due to the fact that Package Manager does not provide an interactive terminal or dialog where you can enter your username and password for HTTP, or your passphrase to unlock your SSH key:
-
With HTTP(S), every time you log onto BitBucket, GitHub or GitLab you need to enter your username and password in a terminal or a dialog box. However, the Package Manager does not provide an interactive terminal or dialog where you can enter your username and password for HTTP(S).
To bypass this, use one of the workarounds suggested in Solutions for HTTPS.
-
SSH uses a pair of public and private SSH keys. You can add your public SSH key to Bitbucket, GitHub or GitLab and then access repositories without having to enter a username and password.
However, if you have set up a passphrase to keep your SSH key safe, you still have to enter that passphrase in a terminal or a dialog box in order to authorize your key. In that case, you can use an SSH agent that can unlock your SSH key to authenticate with the Package Manager on your behalf.
Solutions for HTTPS
The Package Manager does not provide an interactive terminal or dialog where you can enter your HTTP(S) username and password. To bypass this, use one of these workarounds:
- Use a credential manager (Git Credential Manager for Windows or OSXKeyChain). Credential managers handle sending the password without having to use a terminal or a command prompt.
- Use git-credentials from a terminal or command prompt. Then launch the Hub from the same terminal so that Unity has access to the cached or stored credentials.
- Use SSH to authenticate instead. If you set up your SSH key without a passphrase, the Package Manager doesn’t have to decrypt it in order to authenticate with the Git server. If you decide to use a passphrase for added security, you can still get around the authentication problem by using the ssh-agent on either macOS or Windows.
Solutions for SSH
If you are using the SSH protocol to install a package by Git URL, you might get an authentication error from Git. This typically happens when you set up a private SSH key on your local machine that is protected by a passphrase.
The solution to this problem is to set up an SSH agent that can unlock your SSH key to authenticate with the Package Manager on your behalf. Follow the instructions in the section that corresponds to your operating system:
- Setting up OpenSSH for Windows
- Adding SSH keys to your SSH Agent for macOS
Setting up OpenSSH for Windows
The native Windows OpenSSH version of the ssh-agent works better than the version available by default with Git for Windows. This procedure explains how to set up the OpenSSH client and add your key to its ssh-agent. If you are using Git for Windows, you can also prioritize the native Windows OpenSSH over the Git for Windows SSH agent:
-
Make sure the OpenSSH Client is installed by searching for it in the Windows Settings Optional features window (Start > Settings, then search for “Optional features”). This applies to Windows 10+.
-
Check your
%PATH%
environment variable to make sure the native Windows OpenSSH location appears (for example,C:WINDOWSSystem32OpenSSH
).Note: If you are already using Git for Windows, make sure the native Windows OpenSSH location appears before the Git for Windows SSH location in your
%PATH%
variable. This ensures that Windows uses the native Windows OpenSSH agent over the Git for Windows SSH agent. -
In a PowerShell terminal, start the
ssh-agent
process and make sure it starts automatically:# Set the ssh-agent service to start automatically and manually start it now Get-Service ssh-agent | Set-Service -StartupType Automatic # Run the ssh-agent process to start the ssh-agent service ssh-agent
-
Import your key into the ssh-agent by running
ssh-add
on the command line and then following the instructions. By default, the agent adds the%USERPROFILE%.sshid_rsa
key and prompts you for the password.# Import the key ssh-add
To use a different key, you can specify it as an argument:
# Set the ssh-agent service to start automatically and manually start it now ssh-add <your-secure-ssh-key-name>
If you can’t remember the name of your key, you can ask the agent to list them:
ssh-add -l
-
If you installed Git for Windows, reset the
%GIT-SSH%
environment variable to make sure that Git always uses the native Windows OpenSSH version of the ssh-agent:[Environment]::SetEnvironmentVariable("GIT_SSH", "$((Get-Command ssh).Source)", [System.EnvironmentVariableTarget]::User)
Adding SSH keys to your SSH Agent for macOS
Use the ssh-add
command to add your SSH keys to the ssh-agent running on your macOS system. The command parameter you use depends on your version of macOS:
-
Prior to macOS 12, use:
ssh-add -K ~/.ssh/<your-secure-ssh-key-name>
-
Starting with macOS 12, use:
ssh-add --apple-use-keychain ~/.ssh/<your-secure-ssh-key-name>
After you run this command, the terminal asks for the password to unlock your SSH key and then adds it to the macOS keychain. However, once you restart your system, every key stored in the ssh-agent is reset.
To prevent re-entering your password after restarting your system, open the ~/.ssh/config
file (or create one if you don’t find it), and add the following:
Host *
UseKeychain yes
AddKeysToAgent yes
IdentityFile ~/.ssh/<your-secure-ssh-key-name>
Restart your machine to apply these changes.
Can’t update Git version
If you are trying to update your Git dependencyThe Package Manager retrieves Git dependencies from a Git repository directly rather than from a package registry. Git dependencies use a Git URL reference instead of a version, and there’s no guarantee about the package quality, stability, validity, or even whether the version stated in its package.json
file respects Semantic Versioning rules with regards to officially published releases of this package. More info
See in Glossary to a newer version from the repository, but it’s not working, it’s probably because your Git dependency is locked. If you want to update your Git dependency to a newer version from the repository, use the Add package from git URL button and enter a Git URL. For more information, see Locked Git dependencies.
‘Failed to parse Http response’ in My Assets context
If you see the following message in the Console window when trying to download an Asset Store package, there might be a problem with your Asset Store cache:
[PackageManager] Error Failed to parse response. UnityEditor.AsyncHTTPClient![:D](https://forum.unity.com/styles/default/xenforo/clear.png)one(State, Int32)
To solve this problem, delete all downloaded assets from the Asset Store package directory and then try downloading the assets again.
Warning: If your project contains a lot of asset data, this might take a lot of time and bandwidth to re-download everything.
Missing ‘My Registries’ in the Package Manager window
Not all registry providers are compatible with Unity’s Package Manager. If the package registry server you added does not implement the /-/v1/search
or /-/all
endpoints, your scoped registry is not compatible with Unity’s Package Manager, and doesn’t appear in the My Registries context in the Package Manager window.
Missing MonoBehaviour errors
While building, if there are a lot of errors about Missing Behavior, the UnityLinker might be mistakenly stripping out a component that it thinks is unreferenced. It often does this because the stripping level is too aggressive. For example, if you have a prefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary in an AssetBundle that references the SpriteShape component in the 2D SpriteShape package, the object might be missing and might generate compiler warnings.
To fix this, you can either lower the stripping level for the UnityLinker or declare the package’s assemblies inside the link.xml
file in order to preserve them from being stripped:
<linker>
<assembly fullname="Unity.2D.SpriteShape.Runtime" preserve="all"/>
<assembly fullname="Unity.2D.Common.Runtime" preserve="all"/>
</linker>
For more information on stripping levels and the UnityLinker, see Managed code stripping.
Loading error for hostfxr.dll on Windows
If the Console reports that the hostfxr.dll
library was found, but Unity failed to load it from C:<path_to_app>hostfxr.dll
, you can fix this error on Windows 7 or Windows Server 2008 R2 by installing both KB2999226 and KB2533623 patches.
Local folder or tarball paths
Подскажите плиз, что делать..
Вот код:
using System.Collections;
using UnityEngine;
public class Name : MonoBehaviour
{
public string Url;
public GUIText status;
WebViewObject webViewObject;
IEnumerator Start()
{
webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
webViewObject.Init(
cb: (msg) =>
{
Debug.Log(string.Format("CallFromJS[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play(webViewObject);
},
err: (msg) =>
{
Debug.Log(string.Format("CallOnError[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play(webViewObject);
},
started: (msg) =>
{
Debug.Log(string.Format("CallOnStarted[{0}]", msg));
},
ld: (msg) =>
{
Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
// NOTE: depending on the situation, you might prefer
// the 'iframe' approach.
// cf. https://github.com/gree/unity-webview/issues/189
#if true
webViewObject.EvaluateJS(@"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
window.location = 'unity:' + msg;
}
}
}
");
#else
webViewObject.EvaluateJS(@"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'unity:' + msg);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}
}
");
#endif
#endif
webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)");
},
//ua: "custom user agent string",
enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
webViewObject.bitmapRefreshCycle = 1;
#endif
webViewObject.SetMargins(5, 100, 5, Screen.height / 4);
webViewObject.SetVisibility(true);
#if !UNITY_WEBPLAYER
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
var exts = new string[]{
".jpg",
".js",
".html" // should be last
};
foreach (var ext in exts) {
var url = Url.Replace(".html", ext);
var src = System.IO.Path.Combine(Application.streamingAssetsPath, url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, url);
byte[] result = null;
if (src.Contains("://")) { // for Android
var www = new WWW(src);
yield return www;
result = www.bytes;
} else {
result = System.IO.File.ReadAllBytes(src);
}
System.IO.File.WriteAllBytes(dst, result);
if (ext == ".html") {
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
break;
}
}
}
#else
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
}
webViewObject.EvaluateJS(
"parent.$(function() {" +
" window.Unity = {" +
" call:function(msg) {" +
" parent.unityWebView.sendMessage('WebViewObject', msg)" +
" }" +
" };" +
"});");
#endif
yield break;
}
#if !UNITY_WEBPLAYER
void OnGUI()
{
GUI.enabled = webViewObject.CanGoBack();
if (GUI.Button(new Rect(10, 10, 80, 80), "<")) {
webViewObject.GoBack();
}
GUI.enabled = true;
GUI.enabled = webViewObject.CanGoForward();
if (GUI.Button(new Rect(100, 10, 80, 80), ">")) {
webViewObject.GoForward();
}
GUI.enabled = true;
GUI.TextField(new Rect(200, 10, 300, 80), "" + webViewObject.Progress());
}
#endif
}
Here are the examples of the csharp api UnityEngine.Debug.LogError(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
[ImageEffectTransformsToLDR]
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
return;
}
#if UNITY_EDITOR
validRenderTextureFormat = true;
if (source.format != RenderTextureFormat.ARGBHalf)
{
validRenderTextureFormat = false;
}
#endif
// clamp some values to not go out of a valid range
exposureAdjustment = exposureAdjustment < 0.001f ? 0.001f : exposureAdjustment;
// SimpleReinhard tonemappers (local, non adaptive)
if (type == TonemapperType.UserCurve)
{
float rangeScale = UpdateCurve();
tonemapMaterial.SetFloat("_RangeScale", rangeScale);
tonemapMaterial.SetTexture("_Curve", curveTex);
Graphics.Blit(source, destination, tonemapMaterial, 4);
return;
}
if (type == TonemapperType.SimpleReinhard)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 6);
return;
}
if (type == TonemapperType.Hable)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 5);
return;
}
if (type == TonemapperType.Photographic)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 8);
return;
}
if (type == TonemapperType.OptimizedHejiDawson)
{
tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f*exposureAdjustment);
Graphics.Blit(source, destination, tonemapMaterial, 7);
return;
}
// still here?
// => adaptive tone mapping:
// builds an average log luminance, tonemaps according to
// middle grey and white values (user controlled)
// AdaptiveReinhardAutoWhite will calculate white value automagically
bool freshlyBrewedInternalRt = CreateInternalRenderTexture(); // this retrieves rtFormat, so should happen before rt allocations
RenderTexture rtSquared = RenderTexture.GetTemporary((int) adaptiveTextureSize, (int) adaptiveTextureSize, 0, rtFormat);
Graphics.Blit(source, rtSquared);
int downsample = (int) Mathf.Log(rtSquared.width*1.0f, 2);
int div = 2;
var rts = new RenderTexture[downsample];
for (int i = 0; i < downsample; i++)
{
rts[i] = RenderTexture.GetTemporary(rtSquared.width/div, rtSquared.width/div, 0, rtFormat);
div *= 2;
}
// downsample pyramid
var lumRt = rts[downsample - 1];
Graphics.Blit(rtSquared, rts[0], tonemapMaterial, 1);
if (type == TonemapperType.AdaptiveReinhardAutoWhite)
{
for (int i = 0; i < downsample - 1; i++)
{
Graphics.Blit(rts[i], rts[i + 1], tonemapMaterial, 9);
lumRt = rts[i + 1];
}
}
else if (type == TonemapperType.AdaptiveReinhard)
{
for (int i = 0; i < downsample - 1; i++)
{
Graphics.Blit(rts[i], rts[i + 1]);
lumRt = rts[i + 1];
}
}
// we have the needed values, let's apply adaptive tonemapping
adaptionSpeed = adaptionSpeed < 0.001f ? 0.001f : adaptionSpeed;
tonemapMaterial.SetFloat("_AdaptionSpeed", adaptionSpeed);
rt.MarkRestoreExpected(); // keeping luminance values between frames, RT restore expected
#if UNITY_EDITOR
if (Application.isPlaying && !freshlyBrewedInternalRt)
Graphics.Blit(lumRt, rt, tonemapMaterial, 2);
else
Graphics.Blit(lumRt, rt, tonemapMaterial, 3);
#else
Graphics.Blit (lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2);
#endif
middleGrey = middleGrey < 0.001f ? 0.001f : middleGrey;
tonemapMaterial.SetVector("_HdrParams", new Vector4(middleGrey, middleGrey, middleGrey, white*white));
tonemapMaterial.SetTexture("_SmallTex", rt);
if (type == TonemapperType.AdaptiveReinhard)
{
Graphics.Blit(source, destination, tonemapMaterial, 0);
}
else if (type == TonemapperType.AdaptiveReinhardAutoWhite)
{
Graphics.Blit(source, destination, tonemapMaterial, 10);
}
else
{
Debug.LogError("No valid adaptive tonemapper type found!");
Graphics.Blit(source, destination); // at least we get the TransformToLDR effect
}
// cleanup for adaptive
for (int i = 0; i < downsample; i++)
{
RenderTexture.ReleaseTemporary(rts[i]);
}
RenderTexture.ReleaseTemporary(rtSquared);
}
public void Convert ( Texture2D temp2DTex, string path) {
// conversion fun: the given 2D texture needs to be of the format
// w * h, wheras h is the 'depth' (or 3d dimension 'dim') and w = dim * dim
if (temp2DTex) {
int dim = temp2DTex.width * temp2DTex.height;
dim = temp2DTex.height;
if (!ValidDimensions(temp2DTex)) {
Debug.LogWarning ("The given 2D texture " + temp2DTex.name + " cannot be used as a 3D LUT.");
basedOnTempTex = "";
return;
}
var c = temp2DTex.GetPixels();
var newC = new Color[c.Length];
for(int i = 0; i < dim; i++) {
for(int j = 0; j < dim; j++) {
for(int k = 0; k < dim; k++) {
int j_ = dim-j-1;
newC[i + (j*dim) + (k*dim*dim)] = c[k*dim+i+j_*dim*dim];
}
}
}
if (converted3DLut)
DestroyImmediate (converted3DLut);
converted3DLut = new Texture3D (dim, dim, dim, TextureFormat.ARGB32, false);
converted3DLut.SetPixels (newC);
converted3DLut.Apply ();
basedOnTempTex = path;
}
else {
// error, something went terribly wrong
Debug.LogError ("Couldn't color correct with 3D LUT texture. Image Effect will be disabled.");
}
}
public bool Handle()
{
int count = hashData.Count;
for (int i = 0; i < count; i++)
{
PhotonView view = PhotonView.Find(hashViews.Dequeue());
if (view == null)
{
//Message what view ID not exists
//Maybe put spam for invalid viewIDs, like 100 per second, idk
return true;
}
else if (view.prefix > 0 && correctPrefix != view.prefix)
{
Debug.LogError(string.Concat(new object[] { "Received OnSerialization for view ID ", view.viewID, " with prefix ", correctPrefix, ". Our prefix is ", view.prefix }));
}
if (view.observed == null)
{
myReason = $"OSR: Null observed for ViewID[{view.viewID.ToString()}]";
return false;
}
if (view.observed is MonoBehaviour)
{
PhotonStream pStream = new PhotonStream(false, hashData.Dequeue());
PhotonMessageInfo info = new PhotonMessageInfo(sender, sentTime, view);
view.ExecuteOnSerialize(pStream, info);
}
else if (view.observed is Transform)
{
Transform tf = (Transform)view.observed;
object[] arr = hashData.Dequeue();
switch (arr.Length)
{
case 1:
{
if (arr[0] == null || !(arr[0] is Vector3 vec))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
tf.localPosition = vec;
}
break;
case 2:
{
if (arr[0] == null || !(arr[0] is Vector3 vec))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
if (arr[1] == null || !(arr[1] is Quaternion quat))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
tf.localPosition = vec;
tf.localRotation = quat;
break;
}
case 3:
case 4:
{
if (arr[0] == null || !(arr[0] is Vector3 vec))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
if (arr[1] == null || !(arr[1] is Quaternion quat))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
if (arr[2] == null || !(arr[2] is Vector3 vec1))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
tf.localPosition = vec;
tf.localRotation = quat;
tf.localScale = vec1;
break;
}
default:
myReason = $"OSR:Invalid data length(Tf)" + arr.Length.ToString();
return false;
}
}
else if (view.observed is Rigidbody)
{
Rigidbody rb = (Rigidbody)view.observed;
object[] arr = hashData.Dequeue();
switch (arr.Length)
{
case 1:
{
if (arr[0] == null || !(arr[0] is Vector3 vec))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
rb.velocity = vec;
break;
}
case 2:
{
if (arr[0] == null || !(arr[0] is Vector3 vec))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
if (arr[1] == null || !(arr[1] is Vector3 loc))
{
myReason = "OSR: Null or Invalid value inside data";
return false;
}
rb.velocity = vec;
rb.angularVelocity = loc;
break;
}
default:
myReason = "OSR:Invalid data length(Rb) " + arr.Length.ToString();
return false;
}
}
else
{
//Log.Spam($"Recieved unknown observed type by [{sender.ID.ToString()}]", "UnkOSR", sender.ID);
hashData.Dequeue();
}
}
return true;
}
public bool Handle()
{
PhotonView photonView = PhotonView.Find(viewID);
if (photonView == null)
{
return true;
}
if ((photonView.Group != 0) && !PhotonNetwork.networkingPeer.allowedReceivingGroups.Contains(photonView.Group))
{
return true;
}
System.Type[] callParameterTypes = new System.Type[0];
if (parameters.Length > 0)
{
callParameterTypes = new System.Type[parameters.Length];
int index = 0;
for (int i = 0; i < parameters.Length; i++)
{
object obj2 = parameters[i];
if (obj2 == null)
{
callParameterTypes[index] = null;
}
else
{
callParameterTypes[index] = obj2.GetType();
}
index++;
}
}
int num7 = 0;
int num8 = 0;
foreach (MonoBehaviour behaviour in photonView.GetComponents<MonoBehaviour>())
{
if (behaviour == null)
{
Debug.LogError("ERROR You have missing MonoBehaviours on your gameobjects!");
}
else
{
System.Type key = behaviour.GetType();
List<MethodInfo> list = null;
if (PhotonNetwork.networkingPeer.monoRPCMethodsCache.ContainsKey(key))
{
list = PhotonNetwork.networkingPeer.monoRPCMethodsCache[key];
}
if (list == null)
{
List<MethodInfo> methods = SupportClreplaced.GetMethods(key, typeof(UnityEngine.RPC));
PhotonNetwork.networkingPeer.monoRPCMethodsCache[key] = methods;
list = methods;
}
if (list != null)
{
for (int j = 0; j < list.Count; j++)
{
MethodInfo info = list[j];
if (info.Name == name)
{
num8++;
ParameterInfo[] methodParameters = info.GetParameters();
if (methodParameters.Length == callParameterTypes.Length)
{
if (PhotonNetwork.networkingPeer.CheckTypeMatch(methodParameters, callParameterTypes))
{
num7++;
object obj3 = info.Invoke(behaviour, parameters);
if (info.ReturnType == typeof(IEnumerator))
{
behaviour.StartCoroutine((IEnumerator)obj3);
}
}
return true;
}
else if ((methodParameters.Length - 1) == callParameterTypes.Length)
{
if (PhotonNetwork.networkingPeer.CheckTypeMatch(methodParameters, callParameterTypes) && (methodParameters[methodParameters.Length - 1].ParameterType == typeof(PhotonMessageInfo)))
{
num7++;
object[] array = new object[parameters.Length + 1];
parameters.CopyTo(array, 0);
array[array.Length - 1] = new PhotonMessageInfo(sender, sTime, photonView);
object obj4 = info.Invoke(behaviour, array);
if (info.ReturnType == typeof(IEnumerator))
{
behaviour.StartCoroutine((IEnumerator)obj4);
}
}
return true;
}
else if ((methodParameters.Length == 1) && methodParameters[0].ParameterType.IsArray)
{
num7++;
object[] objArray5 = new object[] { parameters };
object obj5 = info.Invoke(behaviour, objArray5);
if (info.ReturnType == typeof(IEnumerator))
{
behaviour.StartCoroutine((IEnumerator)obj5);
}
return true;
}
return false;
}
//Log.AddLineRaw("Unknown RPC: " + name + " by ID " + sender.ID);
}
}
}
}
return true;
}
public void Load()
{
if (!System.IO.File.Exists(Path))
{
Debug.LogError($"ConfigFile Error: There is no file {Path}.");
return;
}
allValues.Clear();
booleans.Clear();
floats.Clear();
integers.Clear();
strings.Clear();
string[] allStrings = System.IO.File.ReadAllLines(Path);
foreach (string str in allStrings)
{
if (str.StartsWith("#") || str.Equals(string.Empty))
{
continue;
}
string[] add = ParseString(str);
if (add == null)
{
continue;
}
allValues.Add(add[0], add[1]);
}
}
public static void SetLanguage(string lang)
{
if (AllLanguages.Contains(lang))
{
Directory = Path + lang + "/";
SelectedLanguage = lang;
Reload();
return;
}
Debug.LogError("Not found language: " + lang);
SetLanguage(DefaultLanguage);
}
public bool Handle()
{
GameObject res = key.StartsWith("RCreplacedet/") ? CacheResources.RCLoad(key) : (GameObject)CacheResources.Load(key);
if (res == null)
{
return false;
}
PhotonView[] photonViewsInChildren = res.GetPhotonViewsInChildren();
if (photonViewsInChildren.Length != instIDs.Length)
{
throw new System.Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data.");
}
for (int i = 0; i < instIDs.Length; i++)
{
photonViewsInChildren[i].viewID = instIDs[i];
photonViewsInChildren[i].prefix = prefix;
photonViewsInChildren[i].instantiationId = instID;
}
PhotonNetwork.networkingPeer.StoreInstantiationData(instID, data);
GameObject obj2 = (GameObject)UnityEngine.Object.Instantiate(res, position, rotation);
for (int j = 0; j < instIDs.Length; j++)
{
photonViewsInChildren[j].viewID = 0;
photonViewsInChildren[j].prefix = -1;
photonViewsInChildren[j].prefixBackup = -1;
photonViewsInChildren[j].instantiationId = -1;
}
PhotonNetwork.networkingPeer.RemoveInstantiationData(instID);
if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(instID))
{
GameObject go = PhotonNetwork.networkingPeer.instantiatedObjects[instID];
string str2 = string.Empty;
if (go != null)
{
foreach (PhotonView view in go.GetPhotonViewsInChildren())
{
if (view != null)
{
str2 = str2 + view.ToString() + ", ";
}
}
}
object[] args = new object[] { obj2, instID, PhotonNetwork.networkingPeer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count };
Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args));
PhotonNetwork.networkingPeer.RemoveInstantiatedGO(go, true);
}
PhotonNetwork.networkingPeer.instantiatedObjects.Add(instID, obj2);
obj2.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(sender, timeStamp, null), SendMessageOptions.DontRequireReceiver);
return true;
}
private void Awake()
{
if (Instance != null)
{
Debug.LogError($"There should be only one instance of "UIManager". Please make sure yo spawn it just once.");
DestroyImmediate(this);
return;
}
DontDestroyOnLoad(this);
Instance = this;
onAwakeAdds();
onAwakeRms();
onAwakeAdds = delegate () { };
onAwakeRms = delegate () { };
}
[GUIPage(CreationPage)]
private void RoomCreation()
{
left.Reset();
right.Reset();
LabelCenter(left, locale["roomSettings"], true);
serverName = TextField(left, serverName, locale["roomName"], Style.LabelOffset, true);
preplacedword = TextField(left, preplacedword, locale["pwd"], Style.LabelOffset, true);
serverTime = TextField(left, serverTime, locale["time"], Style.LabelOffset * 2f, true);
maxPlayers = TextField(left, maxPlayers, locale["players"], Style.LabelOffset * 2f, true);
LabelCenter(left, locale["difficulity"], true);
difficulity = SelectionGrid(left, difficulity, difficulities, difficulities.Length, true);
LabelCenter(left, locale["dayLight"], true);
daylight = SelectionGrid(left, daylight, daylights, daylights.Length, true);
left.MoveY();
LabelCenter(left, locale["presets"], true);
Label(left, locale["presetNote"], true);
newPresetName = TextField(left, newPresetName, locale["presetName"], Style.LabelOffset, true);
left.width = (left.DefaultWidth - Style.HorizontalMargin) / 2f;
if (Button(left, locale["presetAdd"], false))
{
ServerPreset set = new ServerPreset(newPresetName);
ExportPreset(set);
presets.Add(set);
presetView.height = (presets.Count * Style.Height) + ((presets.Count - 1) * Style.VerticalMargin);
set.Save();
}
left.MoveX();
if (Button(left, locale["presetRemove"], true))
{
if (presets.Count > 1)
{
ServerPreset selected = null;
for (int i = 0; i < presets.Count; i++)
{
if (presets[i].Name == newPresetName)
{
selected = presets[i];
}
}
if (selected != null)
{
presets.Remove(selected);
selected.Delete();
newPresetName = "Set " + (presets.Count + 1);
if (presets.Count > 0)
{
newPresetName = presets[presets.Count - 1].Name;
}
presetView.height = (presets.Count * Style.Height) + ((presets.Count - 1) * Style.VerticalMargin);
}
}
}
left.ResetX();
if (presets.Count > 0)
{
presetArea.y = left.y;
presetRect.Reset();
presetScroll = BeginScrollView(presetArea, presetScroll, presetView);
{
for (int i = 0; i < presets.Count; i++)
{
if (Button(presetRect, presets[i].Name, true))
{
ServerPreset selected = presets[i];
ImportPreset(selected);
}
}
}
EndScrollView();
}
left.MoveToEndY(WindowPosition, Style.Height);
left.width = left.DefaultWidth / 2f - Style.HorizontalMargin;
if (Button(left, locale["btnCreation"], false))
{
disconnectByJoin = true;
serverTime = serverTime.Trim();
int serverTimeInt;
if(!int.TryParse(serverTime, out serverTimeInt))
{
serverTimeInt = 120;
}
daylight = daylight > 2 ? 0 : daylight;
difficulity = difficulity > 2 ? 0 : difficulity;
string mapName = string.Empty;
try
{
mapName = maps[mapSelectionSetting];
}
catch(System.Exception ex)
{
Debug.LogError("Room creation exception appeared: " + ex.Message + "n" + ex.StackTrace + $"nSetting info: {mapSelectionSetting}");
mapSelectionSetting.Value = 0;
mapName = maps[mapSelectionSetting.Value];
}
string[] args = new string[]
{
serverName,
mapName,
new string[] { "normal", "hard", "abnormal" }[difficulity],
serverTimeInt.ToString(),
new string[] { "day", "dawn", "night" }[daylight],
preplacedword.Length > 0 ? new SimpleAES().Encrypt(preplacedword) : string.Empty,
UnityEngine.Random.Range(1000000, 10000000).ToString()
};
if (!int.TryParse(maxPlayers, out int max))
{
max = 5;
}
PhotonNetwork.CreateRoom(string.Join("`", args), new RoomOptions() { isVisible = true, isOpen = true, maxPlayers = max }, null);
DisableImmediate();
AnarchyManager.Background.Disable();
return;
}
left.MoveX(Style.HorizontalMargin, true);
if (Button(left, locale["btnOffline"], false))
{
disconnectByJoin = true;
PhotonNetwork.Disconnect();
PhotonNetwork.offlineMode = true;
string[] args = new string[]
{
serverName,
maps[mapSelectionSetting.Value],
new string[] { "normal", "hard", "abnormal" }[difficulity],
serverTime,
new string[] { "day", "dawn", "night" }[daylight],
preplacedword.Length > 0 ? new SimpleAES().Encrypt(preplacedword) : string.Empty,
UnityEngine.Random.Range(1000000, 10000000).ToString()
};
if (!int.TryParse(maxPlayers, out int max))
{
max = 5;
}
PhotonNetwork.CreateRoom(string.Join("`", args), new RoomOptions() { isVisible = true, isOpen = true, maxPlayers = max }, null);
DisableImmediate();
AnarchyManager.Background.Disable();
return;
}
LabelCenter(right, locale["mapSelection"], true);
//mapSelection = SelectionGrid(right, mapSelection, maps, 1);
DropdownMenuScrollable(this, right, mapSelectionSetting, maps, 10, true);
right.MoveY();
right.MoveY();
Label(right, LevelInfo.GetInfo(maps[mapSelectionSetting.Value], false).Description, true);
right.MoveToEndY(WindowPosition, Style.Height);
right.MoveToEndX(WindowPosition, new AutoScaleFloat(240f) + Style.HorizontalMargin);
right.width = new AutoScaleFloat(120f);
if (Button(right, locale["btnSettings"], false))
{
connected = false;
pageSelection = SettingsPage;
return;
}
right.MoveX();
if (Button(right, locale["btnList"], false))
{
connected = PhotonNetwork.connected;
if (connected)
{
timeToUpdate = 0.1f;
}
pageSelection = ServerListPage;
return;
}
}
private static int GetLayer(int layerToSet, string name)
{
lock (usedLayers)
{
if (layerToSet >= 0)
{
if (usedLayers.Contains(layerToSet))
{
Debug.LogError($"Attemption to create GUIBase with already existing layer. Please make sure you wanted to use this one. Layer: {layerToSet}, GUIBase name: {name}");
return GetLayer(++layerToSet, name);
}
usedLayers.Add(layerToSet);
UpdateMaxLayer();
return layerToSet;
}
maxLayer = usedLayers.Max();
usedLayers.Add(++maxLayer);
return maxLayer;
}
}
public Texture2D LoadTexture(string namebase, string ext)
{
if (textureCache.TryGetValue(namebase, out Texture2D res) && res != null)
{
return res;
}
string name = namebase;
bool error = false;
if (ext == string.Empty)
{
if (!name.EndsWith(".png") && !name.EndsWith(".jpg") && !name.EndsWith(".jpeg"))
{
error = true;
}
}
else
{
if (!ext.Equals("png") && !ext.Equals("jpg") && !ext.Equals("jpeg"))
{
error = true;
}
name += "." + ext;
}
if (error)
{
Debug.LogError($"You should use png, jpg or jpeg extensions for loading Texture2D");
return Texture2D.blackTexture;
}
string path = Directory + name;
if (!File.Exists(path))
{
Debug.LogError($"File what you are trying to load doesnt't exist: "{path}"");
return Texture2D.blackTexture;
}
res = new Texture2D(1, 1, TextureFormat.RGBA32, false);
res.LoadImage(File.ReadAllBytes(path));
res.Apply();
textureCache.Add(namebase, res);
return res;
}
public MovieTexture LoadVideo(string namebase)
{
MovieTexture tex;
string name = namebase;
string path = Directory + name + ".ogv";
if (!File.Exists(path))
{
Debug.LogError($"File what you are trying to load doesnt't exist: "{path}"");
return null;
}
WWW www = new WWW("file://" + path);
if (www.texture == null)
{
Debug.LogError($"Null texture");
www.Dispose();
GC.SuppressFinalize(www);
return null;
}
tex = www.movie;
www.Dispose();
GC.SuppressFinalize(www);
return tex;
}
public static System.Collections.IEnumerator LoadreplacedetBundle()
{
replacedetBundleCreateRequest bundle = replacedetBundle.CreateFromMemory(File.ReadAllBytes(BundlePath));
yield return bundle;
if (bundle == null)
{
Debug.LogError($"Error while loading Anarchyreplacedets. Make sure that file "{BundlePath}" exists.");
yield break;
}
Bundle = bundle.replacedetBundle;
}
[RPC]
private void loadskinRPC(string url, PhotonMessageInfo info = null)
{
if (SkinSettings.replacedanSkins.Value == 1 && info != null && info.Sender.IsMasterClient && Anarchy.Network.Antis.IsValidSkinURL(ref url, 1, info.Sender.ID))
{
if (mySkin != null)
{
Debug.LogError($"Someone tries to reload existing {GetType().Name} skin");
return;
}
StartCoroutine(LoadMySkin(url));
}
}
[RPC]
private void loadskinRPC(string url, PhotonMessageInfo info = null)
{
if(SkinSettings.replacedanSkins.Value == 1 && info != null && info.Sender.IsMasterClient)
{
if(mySkin != null)
{
Debug.LogError($"Someone tries to reload existing {GetType().Name} skin");
return;
}
StartCoroutine(LoadMySkin(url));
}
}
public void OnPhotonCreateRoomFailed(AOTEventArgs args)
{
Debug.LogError("OnPhotonCreateRoomFailed");
}
private void Awake()
{
if (instance != null)
{
DestroyImmediate(this);
Debug.LogError("Attemption to create more then one Anarchy.InputManager, please avoid this");
return;
}
DontDestroyOnLoad(this);
instance = this;
if (AllKeys == null)
{
InitList();
}
onAwake?.Invoke();
onAwake = null;
}
public void MultiplayerRacingFinish()
{
Debug.LogError(nameof(MultiplayerRacingFinish));
var num = logic.RoundTime - ((RacingLogic)logic).StartTime;
if (PhotonNetwork.IsMasterClient)
{
getRacingResult(User.RaceName, num);
}
else
{
BasePV.RPC("getRacingResult", PhotonTargets.MasterClient, User.RaceName, num);
}
GameWin();
}
public void Set(BetterList<Vector3> verts, BetterList<Vector3> norms, BetterList<Vector4> tans, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
int size = verts.size;
if (size > 0 && size == uvs.size && size == cols.size && size % 4 == 0)
{
if (this.mFilter == null)
{
this.mFilter = base.gameObject.GetComponent<MeshFilter>();
}
if (this.mFilter == null)
{
this.mFilter = base.gameObject.AddComponent<MeshFilter>();
}
if (this.mRen == null)
{
this.mRen = base.gameObject.GetComponent<MeshRenderer>();
}
if (this.mRen == null)
{
this.mRen = base.gameObject.AddComponent<MeshRenderer>();
this.UpdateMaterials();
}
else if (this.mClippedMat != null && this.mClippedMat.mainTexture != this.mSharedMat.mainTexture)
{
this.UpdateMaterials();
}
if (verts.size < 65000)
{
int num = (size >> 1) * 3;
bool flag = this.mIndices == null || this.mIndices.Length != num;
if (flag)
{
this.mIndices = new int[num];
int num2 = 0;
for (int i = 0; i < size; i += 4)
{
this.mIndices[num2++] = i;
this.mIndices[num2++] = i + 1;
this.mIndices[num2++] = i + 2;
this.mIndices[num2++] = i + 2;
this.mIndices[num2++] = i + 3;
this.mIndices[num2++] = i;
}
}
Mesh mesh = this.GetMesh(ref flag, verts.size);
mesh.vertices = verts.ToArray();
if (norms != null)
{
mesh.normals = norms.ToArray();
}
if (tans != null)
{
mesh.tangents = tans.ToArray();
}
mesh.uv = uvs.ToArray();
mesh.colors32 = cols.ToArray();
if (flag)
{
mesh.triangles = this.mIndices;
}
mesh.RecalculateBounds();
this.mFilter.mesh = mesh;
}
else
{
if (this.mFilter.mesh != null)
{
this.mFilter.mesh.Clear();
}
Debug.LogError("Too many vertices on one panel: " + verts.size);
}
}
else
{
if (this.mFilter.mesh != null)
{
this.mFilter.mesh.Clear();
}
Debug.LogError("UIWidgets must fill the buffer with 4 vertices per quad. Found " + size);
}
}
public void Print(string text, Color32 color, BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, bool encoding, UIFont.SymbolStyle symbolStyle, UIFont.Alignment alignment, int lineWidth, bool premultiply)
{
if (this.mReplacement != null)
{
this.mReplacement.Print(text, color, verts, uvs, cols, encoding, symbolStyle, alignment, lineWidth, premultiply);
}
else if (text != null)
{
if (!this.isValid)
{
Debug.LogError("Attempting to print using an invalid font!");
return;
}
bool isDynamic = this.isDynamic;
if (isDynamic)
{
this.mDynamicFont.textureRebuildCallback = new Font.FontTextureRebuildCallback(this.OnFontChanged);
this.mDynamicFont.RequestCharactersInTexture(text, this.mDynamicFontSize, this.mDynamicFontStyle);
this.mDynamicFont.textureRebuildCallback = null;
}
this.mColors.Clear();
this.mColors.Add(color);
int size = this.size;
Vector2 vector = (size <= 0) ? Vectors.v2one : new Vector2(1f / (float)size, 1f / (float)size);
int size2 = verts.size;
int num = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
int num5 = size + this.mSpacingY;
Vector3 zero = Vectors.zero;
Vector3 zero2 = Vectors.zero;
Vector2 zero3 = Vectors.v2zero;
Vector2 zero4 = Vectors.v2zero;
float num6 = this.uvRect.width / (float)this.mFont.texWidth;
float num7 = this.mUVRect.height / (float)this.mFont.texHeight;
int length = text.Length;
bool flag = encoding && symbolStyle != UIFont.SymbolStyle.None && this.hreplacedymbols && this.sprite != null;
for (int i = 0; i < length; i++)
{
char c = text[i];
if (c == 'n')
{
if (num2 > num)
{
num = num2;
}
if (alignment != UIFont.Alignment.Left)
{
this.Align(verts, size2, alignment, num2, lineWidth);
size2 = verts.size;
}
num2 = 0;
num3 += num5;
num4 = 0;
}
else if (c < ' ')
{
num4 = 0;
}
else
{
if (encoding && c == '[')
{
int num8 = NGUITools.ParseSymbol(text, i, this.mColors, premultiply);
if (num8 > 0)
{
color = this.mColors[this.mColors.Count - 1];
i += num8 - 1;
goto IL_96C;
}
}
if (!isDynamic)
{
BMSymbol bmsymbol = (!flag) ? null : this.MatchSymbol(text, i, length);
if (bmsymbol == null)
{
BMGlyph glyph = this.mFont.GetGlyph((int)c);
if (glyph == null)
{
goto IL_96C;
}
if (num4 != 0)
{
num2 += glyph.GetKerning(num4);
}
if (c == ' ')
{
num2 += this.mSpacingX + glyph.advance;
num4 = (int)c;
goto IL_96C;
}
zero.x = vector.x * (float)(num2 + glyph.offsetX);
zero.y = -vector.y * (float)(num3 + glyph.offsetY);
zero2.x = zero.x + vector.x * (float)glyph.width;
zero2.y = zero.y - vector.y * (float)glyph.height;
zero3.x = this.mUVRect.xMin + num6 * (float)glyph.x;
zero3.y = this.mUVRect.yMax - num7 * (float)glyph.y;
zero4.x = zero3.x + num6 * (float)glyph.width;
zero4.y = zero3.y - num7 * (float)glyph.height;
num2 += this.mSpacingX + glyph.advance;
num4 = (int)c;
if (glyph.channel == 0 || glyph.channel == 15)
{
for (int j = 0; j < 4; j++)
{
cols.Add(color);
}
}
else
{
Color color2 = color;
color2 *= 0.49f;
switch (glyph.channel)
{
case 1:
color2.b += 0.51f;
break;
case 2:
color2.g += 0.51f;
break;
case 4:
color2.r += 0.51f;
break;
case 8:
color2.a += 0.51f;
break;
}
for (int k = 0; k < 4; k++)
{
cols.Add(color2);
}
}
}
else
{
zero.x = vector.x * (float)(num2 + bmsymbol.offsetX);
zero.y = -vector.y * (float)(num3 + bmsymbol.offsetY);
zero2.x = zero.x + vector.x * (float)bmsymbol.width;
zero2.y = zero.y - vector.y * (float)bmsymbol.height;
Rect uvRect = bmsymbol.uvRect;
zero3.x = uvRect.xMin;
zero3.y = uvRect.yMax;
zero4.x = uvRect.xMax;
zero4.y = uvRect.yMin;
num2 += this.mSpacingX + bmsymbol.advance;
i += bmsymbol.length - 1;
num4 = 0;
if (symbolStyle == UIFont.SymbolStyle.Colored)
{
for (int l = 0; l < 4; l++)
{
cols.Add(color);
}
}
else
{
Color32 item = Color.white;
item.a = color.a;
for (int m = 0; m < 4; m++)
{
cols.Add(item);
}
}
}
verts.Add(new Vector3(zero2.x, zero.y));
verts.Add(new Vector3(zero2.x, zero2.y));
verts.Add(new Vector3(zero.x, zero2.y));
verts.Add(new Vector3(zero.x, zero.y));
uvs.Add(new Vector2(zero4.x, zero3.y));
uvs.Add(new Vector2(zero4.x, zero4.y));
uvs.Add(new Vector2(zero3.x, zero4.y));
uvs.Add(new Vector2(zero3.x, zero3.y));
}
else if (this.mDynamicFont.GetCharacterInfo(c, out UIFont.mChar, this.mDynamicFontSize, this.mDynamicFontStyle))
{
zero.x = vector.x * ((float)num2 + UIFont.mChar.vert.xMin);
zero.y = -vector.y * ((float)num3 - UIFont.mChar.vert.yMax + this.mDynamicFontOffset);
zero2.x = zero.x + vector.x * UIFont.mChar.vert.width;
zero2.y = zero.y - vector.y * UIFont.mChar.vert.height;
zero3.x = UIFont.mChar.uv.xMin;
zero3.y = UIFont.mChar.uv.yMin;
zero4.x = UIFont.mChar.uv.xMax;
zero4.y = UIFont.mChar.uv.yMax;
num2 += this.mSpacingX + (int)UIFont.mChar.width;
for (int n = 0; n < 4; n++)
{
cols.Add(color);
}
if (UIFont.mChar.flipped)
{
uvs.Add(new Vector2(zero3.x, zero4.y));
uvs.Add(new Vector2(zero3.x, zero3.y));
uvs.Add(new Vector2(zero4.x, zero3.y));
uvs.Add(new Vector2(zero4.x, zero4.y));
}
else
{
uvs.Add(new Vector2(zero4.x, zero3.y));
uvs.Add(new Vector2(zero3.x, zero3.y));
uvs.Add(new Vector2(zero3.x, zero4.y));
uvs.Add(new Vector2(zero4.x, zero4.y));
}
verts.Add(new Vector3(zero2.x, zero.y));
verts.Add(new Vector3(zero.x, zero.y));
verts.Add(new Vector3(zero.x, zero2.y));
verts.Add(new Vector3(zero2.x, zero2.y));
}
}
IL_96C:;
}
if (alignment != UIFont.Alignment.Left && size2 < verts.size)
{
this.Align(verts, size2, alignment, num2, lineWidth);
size2 = verts.size;
}
}
}
public static void Broadcast(string funcName, object param)
{
if (param == null)
{
Debug.LogError("SendMessage is bugged when you try to preplaced 'null' in the parameter field. It behaves as if no parameter was specified.");
}
else
{
int i = 0;
int count = UIRoot.mRoots.Count;
while (i < count)
{
UIRoot uiroot = UIRoot.mRoots[i];
if (uiroot != null)
{
uiroot.BroadcastMessage(funcName, param, SendMessageOptions.DontRequireReceiver);
}
i++;
}
}
}
public static WWW OpenURL(string url)
{
WWW result = null;
try
{
result = new WWW(url);
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
return result;
}
public static WWW OpenURL(string url, WWWForm form)
{
if (form == null)
{
return NGUITools.OpenURL(url);
}
WWW result = null;
try
{
result = new WWW(url, form);
}
catch (Exception ex)
{
Debug.LogError((ex == null) ? "<null>" : ex.Message);
}
return result;
}
public void AllocateManualPhotonView()
{
PhotonView photonView = base.gameObject.GetPhotonView();
if (photonView == null)
{
Debug.LogError("Can't do manual instantiation without PhotonView component.");
return;
}
int num = PhotonNetwork.AllocateViewID();
photonView.RPC("InstantiateRpc", PhotonTargets.AllBuffered, new object[]
{
num
});
}
public void DebugReturn(DebugLevel level, string message)
{
if (level == DebugLevel.ERROR)
{
Debug.LogError(message);
}
else if (level == DebugLevel.WARNING)
{
Debug.LogWarning(message);
}
else if (level == DebugLevel.INFO && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log(message);
}
else if (level == DebugLevel.ALL && PhotonNetwork.logLevel == PhotonLogLevel.Full)
{
Debug.Log(message);
}
}
private static bool VerifyCreplacedeNetwork()
{
if (connected)
{
return true;
}
Debug.LogError("Cannot send messages when not connected. Either connect to Photon OR use offline mode!");
return false;
}
internal static void RPC(PhotonView view, string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
if (!VerifyCreplacedeNetwork())
{
return;
}
if (room == null)
{
Debug.LogWarning("Cannot send RPCs in Lobby, only processed locally");
return;
}
if (player == null)
{
Debug.LogError("Error; Sending RPC to player null! Aborted "" + methodName + """);
}
if (networkingPeer != null)
{
networkingPeer.RPC(view, methodName, targetPlayer, parameters);
}
else
{
Debug.LogWarning("Could not execute RPC " + methodName + ". Possible scene loading in progress?");
}
}
public static bool CloseConnection(PhotonPlayer kickPlayer)
{
if (!VerifyCreplacedeNetwork())
{
return false;
}
if (!player.IsMasterClient)
{
Debug.LogError("CloseConnection: Only the masterclient can kick another player.");
return false;
}
if (kickPlayer == null)
{
Debug.LogError("CloseConnection: No such player connected!");
return false;
}
RaiseEventOptions raiseEventOptions = new RaiseEventOptions
{
TargetActors = new int[]
{
kickPlayer.ID
}
};
return networkingPeer.OpRaiseEvent(203, null, true, raiseEventOptions);
}
public static bool ConnectUsingSettings(string gameVersion)
{
if (PhotonServerSettings == null)
{
Debug.LogError("Can't connect: Loading settings failed. ServerSettings replacedet must be in any 'Resources' folder as: PhotonServerSettings");
return false;
}
SwitchToProtocol(PhotonServerSettings.Protocol);
networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion);
if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode)
{
offlineMode = true;
return true;
}
if (offlineMode)
{
Debug.LogWarning("ConnectUsingSettings() disabled the offline mode. No longer offline.");
}
offlineMode = false;
isMessageQueueRunning = true;
networkingPeer.IsInitialConnect = true;
if (PhotonServerSettings.HostType == ServerSettings.HostingOption.SelfHosted)
{
networkingPeer.IsUsingNameServer = false;
networkingPeer.MasterServerAddress = PhotonServerSettings.ServerAddress + ":" + PhotonServerSettings.ServerPort;
return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer);
}
if (PhotonServerSettings.HostType == ServerSettings.HostingOption.BestRegion)
{
return ConnectToBestCloudServer(gameVersion);
}
return networkingPeer.ConnectToRegionMaster(PhotonServerSettings.PreferredRegion);
}
public static bool CreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby)
{
if (offlineMode)
{
if (offlineModeRoom != null)
{
Debug.LogError("CreateRoom failed. In offline mode you still have to leave a room to enter another.");
return false;
}
offlineModeRoom = new Room(roomName, roomOptions);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom, new object[0]);
return true;
}
else
{
if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady)
{
Debug.LogError("CreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster.");
return false;
}
return networkingPeer.OpCreateGame(roomName, roomOptions, typedLobby);
}
}
public static void Destroy(PhotonView targetView)
{
if (targetView != null)
{
networkingPeer.RemoveInstantiatedGO(targetView.gameObject, !inRoom);
}
else
{
Debug.LogError("Destroy(targetPhotonView) failed, cause targetPhotonView is null.");
}
}
public static void DestroyAll()
{
if (IsMasterClient)
{
networkingPeer.DestroyAll(false);
}
else
{
Debug.LogError("Couldn't call DestroyAll() as only the master client is allowed to call this.");
}
}
public static void DestroyPlayerObjects(PhotonPlayer targetPlayer)
{
if (targetPlayer == null)
{
Debug.LogError("DestroyPlayerObjects() failed, cause parameter 'targetPlayer' was null.");
}
DestroyPlayerObjects(targetPlayer.ID);
}
public static void DestroyPlayerObjects(int targetPlayerId)
{
if (!VerifyCreplacedeNetwork())
{
return;
}
if (player.IsMasterClient || targetPlayerId == player.ID)
{
networkingPeer.DestroyPlayerObjects(targetPlayerId, false);
}
else
{
Debug.LogError("DestroyPlayerObjects() failed, cause players can only destroy their own GameObjects. A Master Client can destroy anyone's. This is master: " + IsMasterClient);
}
}
public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data)
{
if (!connected || (InstantiateInRoomOnly && !inRoom))
{
Debug.LogError(string.Concat(new object[]
{
"Failed to Instantiate prefab: ",
prefabName,
". Client should be in a room. Current connectionStateDetailed: ",
connectionStateDetailed
}));
return null;
}
GameObject gameObject = prefabName.StartsWith("RCreplacedet/") ? Optimization.Caching.CacheResources.RCLoad(prefabName) : (GameObject)Optimization.Caching.CacheResources.Load(prefabName);
// if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out gameObject))
//{
// gameObject =
// if (UsePrefabCache)
// {
// PrefabCache.Add(prefabName, gameObject);
// }
//}
if (gameObject == null)
{
Debug.LogError("Failed to Instantiate prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)");
return null;
}
if (gameObject.GetComponent<PhotonView>() == null)
{
Debug.LogError("Failed to Instantiate prefab:" + prefabName + ". Prefab must have a PhotonView component.");
return null;
}
Component[] photonViewsInChildren = gameObject.GetPhotonViewsInChildren();
int[] array = new int[photonViewsInChildren.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = AllocateViewID(player.ID);
}
networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, false);
return Optimization.Caching.Pool.NetworkInstantiate(prefabName, position, rotation, array[0], array, networkingPeer.currentLevelPrefix, group, data);
//Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, false);
//return networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, gameObject);
}
public static GameObject InstantiateSceneObject(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data)
{
if (!connected || (InstantiateInRoomOnly && !inRoom))
{
Debug.LogError(string.Concat(new object[]
{
"Failed to InstantiateSceneObject prefab: ",
prefabName,
". Client should be in a room. Current connectionStateDetailed: ",
connectionStateDetailed
}));
return null;
}
if (!IsMasterClient)
{
Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Client is not the MasterClient in this room.");
return null;
}
GameObject gameObject = (GameObject)Optimization.Caching.CacheResources.Load(prefabName);
if (gameObject == null)
{
Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)");
return null;
}
if (gameObject.GetComponent<PhotonView>() == null)
{
Debug.LogError("Failed to InstantiateSceneObject prefab:" + prefabName + ". Prefab must have a PhotonView component.");
return null;
}
Component[] photonViewsInChildren = gameObject.GetPhotonViewsInChildren();
int[] array = AllocateSceneViewIDs(photonViewsInChildren.Length);
if (array == null)
{
Debug.LogError(string.Concat(new object[]
{
"Failed to InstantiateSceneObject prefab: ",
prefabName,
". No ViewIDs are free to use. Max is: ",
MAX_VIEW_IDS
}));
return null;
}
Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, true);
return networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, gameObject);
}
public static bool JoinOrCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby typedLobby)
{
if (offlineMode)
{
if (offlineModeRoom != null)
{
Debug.LogError("JoinOrCreateRoom failed. In offline mode you still have to leave a room to enter another.");
return false;
}
offlineModeRoom = new Room(roomName, roomOptions);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom, new object[0]);
return true;
}
else
{
if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady)
{
Debug.LogError("JoinOrCreateRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster.");
return false;
}
if (string.IsNullOrEmpty(roomName))
{
Debug.LogError("JoinOrCreateRoom failed. A roomname is required. If you don't know one, how will you join?");
return false;
}
return networkingPeer.OpJoinRoom(roomName, roomOptions, typedLobby, true);
}
}
public static bool JoinRandomRoom(Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter)
{
if (offlineMode)
{
if (offlineModeRoom != null)
{
Debug.LogError("JoinRandomRoom failed. In offline mode you still have to leave a room to enter another.");
return false;
}
offlineModeRoom = new Room("offline room", null);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]);
return true;
}
else
{
if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady)
{
Debug.LogError("JoinRandomRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster.");
return false;
}
Hashtable hashtable = new Hashtable();
hashtable.MergeStringKeys(expectedCustomRoomProperties);
if (expectedMaxPlayers > 0)
{
hashtable[byte.MaxValue] = expectedMaxPlayers;
}
return networkingPeer.OpJoinRandomRoom(hashtable, 0, null, matchingType, typedLobby, sqlLobbyFilter);
}
}
[Obsolete("Use overload with roomOptions and TypedLobby parameter.")]
public static bool JoinRoom(string roomName, bool createIfNotExists)
{
if (connectionStateDetailed == PeerState.Joining || connectionStateDetailed == PeerState.Joined || connectionStateDetailed == PeerState.ConnectedToGameserver)
{
Debug.LogError("JoinRoom aborted: You can only join a room while not currently connected/connecting to a room.");
}
else if (room != null)
{
Debug.LogError("JoinRoom aborted: You are already in a room!");
}
else if (roomName == string.Empty)
{
Debug.LogError("JoinRoom aborted: You must specifiy a room name!");
}
else
{
if (offlineMode)
{
offlineModeRoom = new Room(roomName, null);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]);
return true;
}
return networkingPeer.OpJoinRoom(roomName, null, null, createIfNotExists);
}
return false;
}
public static bool JoinRoom(string roomName)
{
if (offlineMode)
{
if (offlineModeRoom != null)
{
Debug.LogError("JoinRoom failed. In offline mode you still have to leave a room to enter another.");
return false;
}
offlineModeRoom = new Room(roomName, null);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom, new object[0]);
return true;
}
else
{
if (networkingPeer.server != ServerConnection.MasterServer || !connectedAndReady)
{
Debug.LogError("JoinRoom failed. Client is not on Master Server or not yet ready to call operations. Wait for callback: OnJoinedLobby or OnConnectedToMaster.");
return false;
}
if (string.IsNullOrEmpty(roomName))
{
Debug.LogError("JoinRoom failed. A roomname is required. If you don't know one, how will you join?");
return false;
}
return networkingPeer.OpJoinRoom(roomName, null, null, false);
}
}
public static void RemoveRPCs(PhotonPlayer targetPlayer)
{
if (!VerifyCreplacedeNetwork())
{
return;
}
if (!targetPlayer.IsLocal && !IsMasterClient)
{
Debug.LogError("Error; Only the MasterClient can call RemoveRPCs for other players.");
return;
}
networkingPeer.OpCleanRpcBuffer(targetPlayer.ID);
}
internal void InternalChangeLocalID(int newID)
{
if (!this.IsLocal)
{
Debug.LogError("ERROR You should never change PhotonPlayer IDs!");
return;
}
var info = GetType().GetField(nameof(ID), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (info != null)
{
info.SetValue(this, newID);
InitializeCounters();
}
targetArray[0] = ID;
}
public static GameObject NetworkInstantiate(string name, Vector3 position, Quaternion rotation, int instantioationId, int[] viewIDs, short prefix = 0, int group = 0, object[] data = null)
{
GameObject res = (name.StartsWith("RCreplacedet/") ? CacheResources.RCLoad(name) : CacheResources.Load(name)) as GameObject;
if (res == null)
{
Debug.LogError($"Pool.NetworkInstantiate(): Cannot fint prefab with name "{name}".");
return null;
}
PhotonView[] views = res.GetPhotonViewsInChildren();
if (views.Length != viewIDs.Length)
{
throw new System.Exception($"Pool.NetworkInstantiate(): Error in Instantiation("{name}")! The resource's PhotonView count is not the same as in incoming data. {views.Length} != {viewIDs.Length}");
}
for (int i = 0; i < views.Length; i++)
{
views[i].viewID = viewIDs[i];
views[i].prefix = prefix;
views[i].instantiationId = instantioationId;
}
PhotonNetwork.networkingPeer.StoreInstantiationData(instantioationId, data);
GameObject go = (GameObject)Object.Instantiate(res, position, rotation);
for (int i = 0; i < views.Length; i++)
{
views[i].viewID = 0;
views[i].prefix = -1;
views[i].instantiationId = -1;
views[i].prefixBackup = -1;
}
PhotonNetwork.networkingPeer.RemoveInstantiationData(instantioationId);
if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(instantioationId))
{
GameObject gameobj = PhotonNetwork.networkingPeer.instantiatedObjects[instantioationId];
string str2 = string.Empty;
if (gameobj != null)
{
foreach (PhotonView view in gameobj.GetPhotonViewsInChildren())
{
if (view != null)
{
str2 = str2 + view.ToString() + ", ";
}
}
}
object[] args = new object[] { gameobj, instantioationId, PhotonNetwork.networkingPeer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count };
Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args));
PhotonNetwork.networkingPeer.RemoveInstantiatedGO(go, true);
}
PhotonNetwork.networkingPeer.instantiatedObjects.Add(instantioationId, go);
return go;
}
public GameObject NetworkEnable(string name, Vector3 position, Quaternion rotation, int group = 0, object[] data = null, bool isSceneObject = false)
{
if (IN_GAME_MAIN_CAMERA.GameType != GameType.MultiPlayer)
{
Debug.LogError($"PoolObject.NetworkEnable(): Failed to NetworkEnable prefab, because GameType is not Multiplayer.");
return null;
}
GameObject go = PickObject(name);
PhotonView pv = go.GetComponent<PhotonView>();
if (pv == null)
{
throw new System.Exception($"PoolObject.NetworkEnable(): Prefab "{name}" has not PhotonView component.");
}
PhotonView[] photonViews = go.GetPhotonViewsInChildren();
int[] viewIDs = new int[photonViews.Length];
for (int i = 0; i < viewIDs.Length; i++)
{
viewIDs[i] = PhotonNetwork.AllocateViewID(PhotonNetwork.player.ID);
}
PhotonNetwork.networkingPeer.SendInstantiate(name, position, rotation, group, viewIDs, data, isSceneObject);
return NetworkInstantiate(name, position, rotation, viewIDs[0], viewIDs, (short)(PhotonNetwork.networkingPeer.currentLevelPrefix > 0 ? PhotonNetwork.networkingPeer.currentLevelPrefix : 0), group, data);
#region Old version
//for (int i = 0; i < photonViews.Length; i++)
//{
// photonViews[i].viewID = viewIDs[i];
// photonViews[i].prefix = prefix;
// photonViews[i].instantiationId = instantiationId;
//}
//if (go.transform != null)
//{
// go.transform.position = position;
// go.transform.rotation = rotation;
//}
//peer.StoreInstantiationData(instantiationId, data);
//go.SetActive(true);
//peer.RemoveInstantiationData(instantiationId);
//if (peer.instantiatedObjects.ContainsKey(instantiationId))
//{
// GameObject gameobj = peer.instantiatedObjects[instantiationId];
// string str2 = string.Empty;
// if (gameobj != null)
// {
// foreach (PhotonView view in gameobj.GetPhotonViewsInChildren())
// {
// if (view != null)
// {
// str2 = str2 + view.ToString() + ", ";
// }
// }
// }
// object[] args = new object[] { gameobj, instantiationId, peer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count };
// Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args));
// peer.RemoveInstantiatedGO(go, true);
//}
//peer.instantiatedObjects.Add(instantiationId, go);
//return go;
#endregion Old version
}
public GameObject NetworkInstantiate(string name, Vector3 position, Quaternion rotation, int instantioationId, int[] viewIDs, short prefix = 0, int group = 0, object[] data = null)
{
GameObject go = PickObject(name);
if (!go.GetComponent<PhotonView>())
{
Debug.LogError($"PoolObject.NetworkInstantiate(): Prefab with name "{name}" has not PhotonView component!");
return null;
}
PhotonView[] views = go.GetPhotonViewsInChildren();
for (int i = 0; i < views.Length; i++)
{
views[i].didAwake = false;
views[i].viewID = 0;
views[i].prefix = prefix;
views[i].instantiationId = instantioationId;
views[i].instantiationData = data;
views[i].didAwake = true;
views[i].viewID = viewIDs[i];
}
if (go.transform)
{
go.transform.position = position;
go.transform.rotation = rotation;
}
go.SetActive(true);
PhotonNetwork.networkingPeer.RemoveInstantiationData(instantioationId);
if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(instantioationId))
{
GameObject gameobj = PhotonNetwork.networkingPeer.instantiatedObjects[instantioationId];
string str2 = string.Empty;
if (gameobj != null)
{
foreach (PhotonView view in gameobj.GetPhotonViewsInChildren())
{
if (view != null)
{
str2 = str2 + view.ToString() + ", ";
}
}
}
object[] args = new object[] { gameobj, instantioationId, PhotonNetwork.networkingPeer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count };
Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args));
PhotonNetwork.networkingPeer.RemoveInstantiatedGO(go, true);
}
PhotonNetwork.networkingPeer.instantiatedObjects.Add(instantioationId, go);
return go;
}
public static bool ConnectToBestCloudServer(string gameVersion)
{
if (PhotonServerSettings == null)
{
Debug.LogError("Can't connect: Loading settings failed. ServerSettings replacedet must be in any 'Resources' folder as: PhotonServerSettings");
return false;
}
if (PhotonServerSettings.HostType == ServerSettings.HostingOption.OfflineMode)
{
return ConnectUsingSettings(gameVersion);
}
networkingPeer.IsInitialConnect = true;
networkingPeer.SetApp(PhotonServerSettings.AppID, gameVersion);
CloudRegionCode bestRegionCodeInPreferences = PhotonHandler.BestRegionCodeInPreferences;
if (bestRegionCodeInPreferences != CloudRegionCode.none)
{
Debug.Log("Best region found in PlayerPrefs. Connecting to: " + bestRegionCodeInPreferences);
return networkingPeer.ConnectToRegionMaster(bestRegionCodeInPreferences);
}
return networkingPeer.ConnectToNameServer();
}
public void AddActiveNode(EffectNode node)
{
if (this.AvailableNodeCount == 0)
{
Debug.LogError("out index!");
}
if (this.AvailableENodes[node.Index] == null)
{
return;
}
this.ActiveENodes[node.Index] = node;
this.AvailableENodes[node.Index] = null;
this.AvailableNodeCount--;
}
public void RemoveActiveNode(EffectNode node)
{
if (this.AvailableNodeCount == this.MaxENodes)
{
Debug.LogError("out index!");
}
if (this.ActiveENodes[node.Index] == null)
{
return;
}
this.ActiveENodes[node.Index] = null;
this.AvailableENodes[node.Index] = node;
this.AvailableNodeCount++;
}
public void UpdateIndices()
{
if (!this.IndexDirty)
{
return;
}
VertexPool pool = this.Vertexsegment.Pool;
if (this.Head != 99999 && this.Head != this.Tail)
{
int num = this.Head;
int num2 = 0;
for (; ; )
{
int num3 = num + 1;
if (num3 == this.MaxElements)
{
num3 = 0;
}
if (num3 * 2 >= 65536)
{
Debug.LogError("Too many elements!");
}
int num4 = this.Vertexsegment.VertStart + num3 * 2;
int num5 = this.Vertexsegment.VertStart + num * 2;
int num6 = this.Vertexsegment.IndexStart + num2 * 6;
pool.Indices[num6] = num5;
pool.Indices[num6 + 1] = num5 + 1;
pool.Indices[num6 + 2] = num4;
pool.Indices[num6 + 3] = num5 + 1;
pool.Indices[num6 + 4] = num4 + 1;
pool.Indices[num6 + 5] = num4;
if (num3 == this.Tail)
{
break;
}
num = num3;
num2++;
}
pool.IndiceChanged = true;
}
this.IndexDirty = false;
}
public void UpdateVertices(Vector3 eyePos)
{
float num = 0f;
float num2 = this.ElemLength * (float)(this.MaxElements - 2);
if (this.Head != 99999 && this.Head != this.Tail)
{
int num3 = this.Head;
int num4 = this.Head;
for (; ; )
{
if (num4 == this.MaxElements)
{
num4 = 0;
}
RibbonTrail.Element element = this.ElementArray[num4];
if (num4 * 2 >= 65536)
{
Debug.LogError("Too many elements!");
}
int num5 = this.Vertexsegment.VertStart + num4 * 2;
int num6 = num4 + 1;
if (num6 == this.MaxElements)
{
num6 = 0;
}
Vector3 lhs;
if (num4 == this.Head)
{
lhs = this.ElementArray[num6].Position - element.Position;
}
else if (num4 == this.Tail)
{
lhs = element.Position - this.ElementArray[num3].Position;
}
else
{
lhs = this.ElementArray[num6].Position - this.ElementArray[num3].Position;
}
Vector3 rhs = eyePos - element.Position;
Vector3 vector = Vector3.Cross(lhs, rhs);
vector.Normalize();
vector *= element.Width * 0.5f;
Vector3 vector2 = element.Position - vector;
Vector3 vector3 = element.Position + vector;
VertexPool pool = this.Vertexsegment.Pool;
float num7;
if (this.StretchType == 0)
{
num7 = num / num2 * Mathf.Abs(this.UVDimensions.y);
}
else
{
num7 = num / num2 * Mathf.Abs(this.UVDimensions.x);
}
Vector2 zero = Vectors.v2zero;
pool.Vertices[num5] = vector2;
pool.Colors[num5] = this.Color;
if (this.StretchType == 0)
{
zero.x = this.LowerLeftUV.x + this.UVDimensions.x;
zero.y = this.LowerLeftUV.y - num7;
}
else
{
zero.x = this.LowerLeftUV.x + num7;
zero.y = this.LowerLeftUV.y;
}
pool.UVs[num5] = zero;
pool.Vertices[num5 + 1] = vector3;
pool.Colors[num5 + 1] = this.Color;
if (this.StretchType == 0)
{
zero.x = this.LowerLeftUV.x;
zero.y = this.LowerLeftUV.y - num7;
}
else
{
zero.x = this.LowerLeftUV.x + num7;
zero.y = this.LowerLeftUV.y - Mathf.Abs(this.UVDimensions.y);
}
pool.UVs[num5 + 1] = zero;
if (num4 == this.Tail)
{
break;
}
num3 = num4;
num += (this.ElementArray[num6].Position - element.Position).magnitude;
num4++;
}
this.Vertexsegment.Pool.UVChanged = true;
this.Vertexsegment.Pool.VertChanged = true;
this.Vertexsegment.Pool.ColorChanged = true;
}
}
See More Examples
Egor12 0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
||||
1 |
||||
18.01.2021, 14:23. Показов 40304. Ответов 16 Метки unity (Все метки)
Здраствуйте может кто то знает. Я создаю игру на движке unity и у меня ошибка CS0246 можете пожалуйста подсказать как её убрать? AssetsSpawner.cs(8,12): error CS0246: The type or namespace name ‘Gameobject’ could not be found (are you missing a using directive or an assembly reference?) вот такая ошибка.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
18.01.2021, 14:23 |
Ответы с готовыми решениями: Как убрать ошибку Как убрать ошибку? Как убрать ошибку? Программа переводит два заданных числа из… ошибка CS0246 в проекте как исправить? 16 |
109 / 81 / 37 Регистрация: 13.01.2016 Сообщений: 395 |
|
18.01.2021, 16:50 |
2 |
Строка 8. GameObject. Вторая часть типа тоже с большой буквы
1 |
0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
|
18.01.2021, 16:58 [ТС] |
3 |
Огромное спасибо но теперь ошибка
0 |
74 / 53 / 24 Регистрация: 19.10.2012 Сообщений: 212 |
|
18.01.2021, 18:10 |
4 |
speed += spawner.speedIncrease * Time.deltaTime; Убери spawner speed += speedIncrease * Time.deltaTime; Добавлено через 28 секунд
1 |
250 / 186 / 68 Регистрация: 04.03.2019 Сообщений: 1,010 |
|
18.01.2021, 18:16 |
5 |
spawner.speedIncreas Spawner с большой буквы.
1 |
Egor12 0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
||||
18.01.2021, 21:29 [ТС] |
6 |
|||
Спасибо большое, но у меня появилась ещё одна ошибка AssetsDownMover.cs(24,23): error CS1061: ‘Transform’ does not contain a definition for ‘postition’ and no accessible extension method ‘postition’ accepting a first argument of type ‘Transform’ could be found (are you missing a using directive or an assembly reference?) что то я так понимаю с ‘Transform’ не так. буду очень благодарен за помощь.
0 |
74 / 53 / 24 Регистрация: 19.10.2012 Сообщений: 212 |
|
18.01.2021, 21:40 |
7 |
Во первых у тебя с верху написана ошибка. ее в переводчик. Instantiate(Blocklines[rand], transform.postition, Quaternion.identity); все красное ошибки твоего кода. Миниатюры
0 |
0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
|
18.01.2021, 22:02 [ТС] |
8 |
Спасибо мне 12 только учусь поэтому у меня столько ошибок ) 2 первые ошибки я уже исправил. А там где postition его просто удалить ? Я не настраивал visual studio под unity потому что не знал что это нужно делать, и не знаю как.
0 |
74 / 53 / 24 Регистрация: 19.10.2012 Сообщений: 212 |
|
18.01.2021, 22:26 |
9 |
Ну Youtube в помощь. Я тоже начал примерно в этом возрасте. Очень давно.
0 |
0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
|
18.01.2021, 22:51 [ТС] |
10 |
Спасибо понял. Так всё таки postition убрать из скрипта ?
0 |
74 / 53 / 24 Регистрация: 19.10.2012 Сообщений: 212 |
|
18.01.2021, 23:41 |
11 |
Сообщение было отмечено Egor12 как решение Решение
Так всё таки postition убрать из скрипта ? написано с ошибкой просто. Добавлено через 4 минуты
0 |
0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
|
19.01.2021, 10:59 [ТС] |
12 |
Хорошо огромное спасибо ))
0 |
0 / 0 / 0 Регистрация: 18.01.2021 Сообщений: 20 |
|
20.01.2021, 14:28 [ТС] |
13 |
Почему-то speedIncrease работает то есть скорость становиться больше со временем, а Spawner не работает он не спавнит BlockLines.
0 |
Eli_To4Ka 0 / 0 / 0 Регистрация: 23.11.2021 Сообщений: 1 |
||||
23.11.2021, 12:37 |
14 |
|||
Ночью сидел писал код, по примеру ютубера… у него все работает у меня нет… cs0246 ошибку выбивает.
0 |
529 / 341 / 196 Регистрация: 18.10.2019 Сообщений: 1,152 |
|
23.11.2021, 14:13 |
15 |
Eli_To4Ka, interactactable. Правильно — interactable.
0 |
Sovock 0 / 0 / 0 Регистрация: 06.02.2022 Сообщений: 1 |
||||
06.02.2022, 16:13 |
16 |
|||
Делал год из интеренета, всё сделал как на ролике, но появляется ошибка: (AssetsscriptsMovePlayer.cs(49,20): error CS1061: ‘Rigidbody’ does not contain a definition for ‘AddForse’ and no accessible extension method ‘AddForse’ accepting a first argument of type ‘Rigidbody’ could be found (are you missing a using directive or an assembly reference?) вот код:
0 |
529 / 341 / 196 Регистрация: 18.10.2019 Сообщений: 1,152 |
|
06.02.2022, 16:18 |
17 |
Sovock, метод правильно называется AddForce
0 |