I'm trying to develop a 3D multiplayer game with Unity. I don't know much about Photon, there are similar questions to the one I'm going to ask, but I still haven't found a solution. I will be glad if you help.
I have two scenes named "menu" and "game". In the menu scene, users make character selection after authenticating with playfab. After completing the selection, they connect to the lobby and set up a room and load the game scene. So far everything is successful. However, when the game scene is loaded, I have difficulty loading the characters selected by the users into the scene.
Here is the code file where I make the users choose their characters:
public class choose : MonoBehaviour {
private GameObject[] characterList;
private int index;
PhotonView PV;
private void Awake()
{
PV = GetComponent<PhotonView>();
}
private void Start()
{
index = PlayerPrefs.GetInt("CharacterSelected");
characterList = new GameObject[transform.childCount];
for (int i=0; i< transform.childCount; i++)
characterList[i] = transform.GetChild(i).gameObject;
foreach (GameObject go in characterList)
go.SetActive (false);
if (characterList [index])
characterList [index].SetActive (true);
}
public void ToggleLeft(){
characterList [index].SetActive (false);
index--;
if (index < 0)
index = characterList.Length - 1;
characterList [index].SetActive (true);
}
public void ToggleRight(){
characterList [index].SetActive (false);
index++;
if (index == characterList.Length)
index = 0;
characterList [index].SetActive (true);
}
public void kaydetbuton() {
PlayerPrefs.SetInt ("CharacterSelected", index);
} }
Here is the code file where I make the characters in the game move:
public class control : MonoBehaviour {
public FixedJoystick LeftJoystick;
private GameObject leftjoystick;
public FixedButton Button;
private GameObject button;
public FixedTouchField TouchField;
private GameObject touchField;
protected ThirdPersonUserControl Control;
protected float CameraAngle;
protected float CameraAngleSpeed = 0.2f;
PhotonView PV;
void Awake()
{
PV = GetComponent<PhotonView>();
}
void Start()
{
if (!PV.IsMine)
return;
Control = GetComponent<ThirdPersonUserControl>();
leftjoystick = GameObject.Find("Fixed Joystick");
if (leftjoystick != null)
{
LeftJoystick = leftjoystick.GetComponent<FixedJoystick>();
}
button = GameObject.Find("Handle (1)");
if (button != null)
{
Button = button.GetComponent<FixedButton>();
}
touchField = GameObject.Find("tfield");
if (touchField != null)
{
TouchField = touchField.GetComponent<FixedTouchField>();
}
}
void FixedUpdate() {
if (PV.IsMine)
{
Control.m_Jump = Button.Pressed;
Control.Hinput = LeftJoystick.Direction.x;
Control.Vinput = LeftJoystick.Direction.y;
CameraAngle += TouchField.TouchDist.x * CameraAngleSpeed;
Camera.main.transform.position = transform.position + Quaternion.AngleAxis(CameraAngle, Vector3.up) * new Vector3(1, 2, 3);
Camera.main.transform.rotation = Quaternion.LookRotation(transform.position + Vector3.up * 2f - Camera.main.transform.position, Vector3.up);
}
} }
There is a game object named "karakteryükle" in the menu scene. The code file named "choose" is in this object. There are 4 characters in this game object. Each character has a code file named "control", photon view, photon transform view, animator view component. And the game object named "karakteryükle" is also available as a prefab in the Resources folder.
I am sharing the picture of the components loaded on each character
I shared a picture of the game object named "karakter yükle"
I'm trying to load "karakter yükle" when the scene named game is loaded
PhotonNetwork.Instantiate("karakteryükle", new Vector3((float)-0.43, (float)1.1, (float)-25.84), Quaternion.identity, 0, null);
Result: The "karakteryükle" is loaded onto the stage, but the same character is loaded for each player, the character chosen by each player is not loaded.
I need your opinion on this.
Each player only knows their own setting for the index, because they use the value set in PlayerPrefs.
private void Start()
{
index = PlayerPrefs.GetInt("CharacterSelected");
}
This works for our local player, no problem there. But what happens when a different player enters the scene.
The playerObject is spawned on each client.
Each client handles that playerObject locally (this is the reason IsMine exist).
Player1 executes index = PlayerPrefs.GetInt(..) on their copy of Player2.
What you can do is send a buffered RPC to set the selected character on those remote copies. We want to buffer the rpc so new players change their remote copies of everyone to the appropriate character.
myPhotonView.RPC("SetCharacterIndex", RpcTarget.OthersBuffered, index);
and the corresponding RPC method
[PunRPC]
private void SetCharacterIndex(int index)
{
// Disable other characters and enable the one at this index
}
In the end you end up with something like
void Start()
{
characterList = new GameObject[transform.childCount];
for (int i=0; i< transform.childCount; i++)
{
characterList[i] = transform.GetChild(i).gameObject;
characterList[i].SetActive(false);
}
if (isMine)
{
index = PlayerPrefs.GetInt("CharacterSelected");
// Notify all remote copies of us to change their index
//
photonView.RPC("SetCharacterIndex", RpcTarget.OthersBuffered, index);
// Set the index locally
//
SetCharacterIndex(index);
}
}
[PunRPC]
private void SetCharacterIndex(int index)
{
if (characterList [index])
characterList [index].SetActive (true);
}
Hopefully that helps clear up the reason this happens (networking can be confusing at times).
Related
I am trying to tag two PUN instantiated game objects with "Player1" and "Player2" tags by looking at their PhotonView ViewIDs through an RPC call. I am able to successfully tag the player 1 game object with the player 1 tag, however, no matter what I try, I am unable to set the player2 tag to the player2 object. The code is networked and running on two Oculus Quest headsets. I can start the application on one Quest and it will assign the Player1 tag properly. However, when I start the application on the second Quest, it spawns a player gameobject, but does not tag the object with the Player2 tag even though the player 2 object's PhotonView matches the "2001" value. Below is the code that I am using to spawn in an XROrigin and a networked representation for each player.
using System;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.XR.Interaction.Toolkit;
public class NetworkPlayerSpawner : MonoBehaviourPunCallbacks
{
public GameObject XROriginPrefab;
[HideInInspector]
public GameObject spawnedPlayerPrefab;
private PhotonView pv;
private void Start()
{
pv = GetComponent<PhotonView>();
}
private void Update()
{
// Debug.Log(PhotonNetwork.CurrentRoom.PlayerCount);
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
var playerCount = PhotonNetwork.CurrentRoom.PlayerCount;
Debug.Log("The player count is: " + playerCount);
var teleportAreas = GameObject.FindGameObjectsWithTag("Floor");
//playerCount = 2;
if (playerCount == 1)
{
XROriginPrefab = Instantiate(XROriginPrefab, new Vector3(0, 2.36199999f, 3.78999996f),
new Quaternion(0, 0, 0, 1));
spawnedPlayerPrefab = PhotonNetwork.Instantiate("Network Player", transform.position, transform.rotation);
//spawnedPlayerPrefab.tag = "Player1";
foreach (GameObject go in teleportAreas)
{
go.AddComponent<TeleportationArea>();
}
}
else
{
XROriginPrefab = Instantiate(XROriginPrefab, new Vector3(-10.3859997f,1.60699999f,10.6400003f),
new Quaternion(0,0,0,1));
spawnedPlayerPrefab = PhotonNetwork.Instantiate("Network Player", transform.position, transform.rotation);
//spawnedPlayerPrefab.tag = "Player2";
//If teleport breaks again, I uncommented this line, so it should be commented out again. Should allow for teleport in User 2's room.
foreach (GameObject go in teleportAreas)
{
go.AddComponent<TeleportationArea>();
}
}
rpcCallTagAssign();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
base.OnPlayerEnteredRoom(newPlayer);
Debug.Log("Remote Player Joined!");
rpcCallTagAssign();
}
public override void OnLeftRoom()
{
base.OnLeftRoom();
PhotonNetwork.Destroy(spawnedPlayerPrefab);
}
[PunRPC]
private void tagAssign()
{
if (spawnedPlayerPrefab.GetComponent<PhotonView>().ViewID==1001)
{
spawnedPlayerPrefab.tag = "Player1";
}
if (spawnedPlayerPrefab.GetComponent<PhotonView>().ViewID==2001)
{
spawnedPlayerPrefab.tag = "Player2";
}
}
private void rpcCallTagAssign()
{
pv.RPC("tagAssign", RpcTarget.AllViaServer);
}
}
I am new to networking with Photon, so any help with resolving this issue would be greatly appreciated. Thank you!
The code needs to run on each player (including the copies). The current code can only change the object you have a reference for (spawnedPlayerPrefab). The easiest way is to add an RPC function on the player. That RPC would get called for each instance of that player across the connected clients.
Script On Player.
[PunRPC]
private void AssignTag()
{
if (photonView.ViewID == 1001)
{
gameObject.tag = "Player1";
}
else if (photonView.ViewID == 2001)
{
gameObject.tag = "Player2";
}
}
In NetworkPlayerSpawner
spawnedPlayerPrefab = PhotonNetwork.Instantiate(...);
spawnedPlayerPrefab.GetComponent<PhotonView>().RPC("AssignTag", RpcTarget.AllBufferedViaServer);
The RPC is buffered so future clients entering after you will set your player copy to the correct tag as well (or vice versa).
Ive a question about how to change spirte images during runtime for a bunch of objects.
So i made a tiny racer 2d game, and therefore you can choose differend themes. You have this option in an integraded menu (not a seperate scene).
My question:
Can i switch the sprites easy during the runtime? Ive made prefabs for each track element - and i changed the sprites of those prefabs, but the change only gets visible, after the scene is reloaded. So i would need to avoid this.
Has someone a solution or a hint how i could do that?
Thanks in advance!
Code:
public class Background_Controller : MonoBehaviour {
public Camera mainCamera;
public Color colorNormal;
public GameObject[] Prefabs;
public Sprite[] normalSprites;
public Sprite[] tronSprites;
// Use this for initialization
void Awake () {
SwitchBackgroundFunction();
}
public void SwitchBackground(string Theme)
{
switch(Theme)
{
case "GreenHell":
PlayerPrefs.SetString("Theme", "Normal");
break;
case "NeonCity":
PlayerPrefs.SetString("Theme", "Tron");
break;
}
SwitchBackgroundFunction();
}
private void SwitchBackgroundFunction()
{
int prefabCount = Prefabs.Length;
if (PlayerPrefs.GetString("Theme") == "Normal")
{
mainCamera.backgroundColor = colorNormal;
for (int i = 0; i <= prefabCount - 1; i++)
{
Prefabs[i].GetComponent<SpriteRenderer>().sprite = normalSprites[i];
}
}
if (PlayerPrefs.GetString("Theme") == "Tron")
{
mainCamera.backgroundColor = Color.black;
for (int i = 0; i <= prefabCount - 1; i++)
{
Prefabs[i].GetComponent<SpriteRenderer>().sprite = tronSprites[i];
}
}
}
// Update is called once per frame
void Update () {
}
}
You can do something along the following lines to swap in a sprite from within your resources folder during runtime.
Sprite spr;
spr = Resources.Load<Sprite>("mysprite"); //insert name and file path to sprite within Resources folder
GetComponent<SpriteRenderer>().sprite = spr;
I am developing a simple 2D game. In game, I've created a prefab for charcaters. and I am changing sprite of prefab runtime. This all execute fine. Now I want to apply click event on a particular prefab clone and want to increase scale of prefab. I am attaching a c# script what I have did till now.
public class ShoppingManager : MonoBehaviour {
public static ShoppingManager instance;
[System.Serializable]
public class Shopping
{
public string CharacterName;
public Sprite CharacterSprite;
}
public GameObject CharacterPrefab;
public Transform CharacterSpacer;
public List<Shopping> ShoppingList;
private CharacterScript NewCharacterScript;
/*********************************************Awake()******************************************/
void Awake()
{
MakeSingleton ();
}
/******************************Create object of the script**********************************/
void MakeSingleton()
{
instance = this;
DontDestroyOnLoad (gameObject);
}
// Use this for initialization
void Start () {
LoadCharacters ();
}
void LoadCharacters()
{
foreach (var characters in ShoppingList) {
GameObject NewCharacter = Instantiate (CharacterPrefab) as GameObject;
NewCharacterScript = NewCharacter.GetComponent<CharacterScript> ();
NewCharacterScript.CharacterName = characters.CharacterName;
NewCharacterScript.Charcater.GetComponent<Image> ().sprite = characters.CharacterSprite;
NewCharacterScript.GetComponent<Button> ().onClick.AddListener (() => CharacterClicked (NewCharacterScript.CharacterName, NewCharacterScript.Charcater));
NewCharacter.transform.SetParent (CharacterSpacer, false);
}
}
void CharacterClicked(string CharacterName, GameObject Char)
{
StartCoroutine (IncreaseScale (Char));
}
IEnumerator IncreaseScale(GameObject TempCharacter)
{
int i = 5;
while (i > 0) {
yield return new WaitForSeconds (0.1f);
Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
TempVector.x = TempVector.x + 0.2f;
TempVector.y = TempVector.y + 0.2f;
TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;
i--;
}
}
}
This code triggers click event and also it increases scale but of last clone, not of clicked prefab clone. What I am missing, I can't understand. What should I correct in this. and Yeah! I am also attaching code of a script that I've added on prefab.
public class CharacterScript : MonoBehaviour {
public string CharacterName;
public GameObject Charcater;
}
create collider for your object attach the script below to it this way each object is responsible for handling its own functionalities like increasing its own size
public class characterFunctionalities: MonoBehaviour{
void OnMouseDown()
{
StartCoroutine (IncreaseScale (this.gameobject));
}
IEnumerator IncreaseScale(GameObject TempCharacter)
{
int i = 5;
while (i > 0) {
yield return new WaitForSeconds (0.1f);
Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
TempVector.x = TempVector.x + 0.2f;
TempVector.y = TempVector.y + 0.2f;
TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;
i--;
}
}
}
Okay so i'm making an infinite runner and the technique I've used is to keep the player static and move and instantiate the platform objects.
For that I've created an Array List of objects that are the platforms.
And then I'm adding them in and spawning them.
I am also translating them along the z-axis and i want to destroy the objects that go below 0 in the z axis and then add another object in replacement.
The problem is that it doesn't translate the objects unless I add another script just to do that and it doesn't destroy or add even if I add another script for translation.
My code is as follows. If you have trouble understanding my problem, please ask I would try to explain again.
I have two scripts.
1) PlatformManager: This one is applied on the empty GameObject and contains the ArrayList.
public class PlatformManager : MonoBehaviour
{
[HideInInspector]
public List<GameObject> platforms = new List<GameObject>(); // List of Platfroms.
public GameObject[] prefab; // Allow user to add as many prefabs through the inspactor.
public static float noOfPlatforms; // a variable to hold how many platoforms.
[HideInInspector]
public static float objectPosition; // Z position of the game object.
[HideInInspector]
public static float objectScale;
// Use this for initialization
void Start ()
{
noOfPlatforms = 6.0f;
objectPosition = 0.0f;
objectScale = 0.0f;
platforms.Add((GameObject)Instantiate(prefab[Random.Range(0,prefab.Length)], new Vector3(0,0,0) ,Quaternion.identity));
//platforms.Add((GameObject)Instantiate(prefab[Random.Range(0, prefab.Length)], new Vector3(0, 0, 40.40114f), Quaternion.identity));
for(int i = 0; i < noOfPlatforms; i++){
objectScale = platforms[platforms.Count-1].transform.localScale.z;
objectPosition = platforms[platforms.Count-1].transform.localPosition.z;
platforms.Add((GameObject)Instantiate(prefab[Random.Range(0,prefab.Length)], new Vector3(0,0,(objectPosition + objectScale)+277f) ,Quaternion.identity));
}
}
// Update is called once per frame
void Update ()
{
}
}
2) PlatformController: This one is supposed to instantiate and destroy and translate the objects.
public class PlatformController : MonoBehaviour {
//private bool canBeDestroy = true; // Flag to check whether the gameObject shoud be destroyed or not.
[HideInInspector]
public PlatformManager managePlateform; // Reference to plateformManager script.
[HideInInspector]
public float plateformSpeed = 10f;
[HideInInspector]
public GameObject allPlatforms;
[HideInInspector]
// Awake is called when the script instance is being loaded.
void Awake()
{
// Accessing the plateformManager script for the Plateform.
managePlateform = GameObject.FindGameObjectWithTag("Platform").GetComponent<PlatformManager>();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
// Get the first platform object.
GameObject firstPlatform = managePlateform.platforms[0];
// Get the last platform object.
GameObject lastPlatform = managePlateform.platforms[managePlateform.platforms.Count - 1];
if (firstPlatform.transform.localPosition.z < 0f)
{
Destroy(firstPlatform.gameObject); // destroy the first plateform gameObject.
managePlateform.platforms.Remove(firstPlatform); // also remove the destroyed object from the list.
// When the game object is destroyed then instantiate one gameobject into list and add at the last point.
managePlateform.platforms.Add((GameObject)Instantiate(managePlateform.prefab[Random.Range(0, managePlateform.prefab.Length)], new Vector3(0, 0, (lastPlatform.transform.localPosition.z + lastPlatform.transform.localScale.z) + 277f), Quaternion.identity));
}
// Move the available platforms in the list along the z-axis
foreach (GameObject platform in managePlateform.platforms)
{
platform.transform.Translate(0, 0, -plateformSpeed * Time.deltaTime);
}
}
}
I am trying to change the Material of wall at run time. I import the model of house from Google Sketchup, which has different materials all in one object (this is shown in the inspector). Whenever I click the next button (>>), it changes the first material of the object. How do I get the references to the other elements? This is what I have so far:
public class Material_GUI : MonoBehaviour {
public Material[] mats;
public GameObject go;
private int index = 0;
// Use this for initialization
void Start () {
go.renderer.material= mats[index];
}
// Update is called once per frame
void Update () {
}
void OnGUI(){
GUILayout.BeginArea(new Rect(Screen.width/2-100,Screen.height-60,200,50));
GUI.Box (new Rect(10,10,190,40),"");
GUI.Label(new Rect(62,20,100,20),"Wall Testing"+(index +1));
if(GUI.Button (new Rect(15,15,30,30),"<<")){
index--;
if(index<0){
index = mats.Length - 1;
}
go.renderer.material = mats[index];
}
if(GUI.Button (new Rect(165,15,30,30),">>")){
index++;
if(index > mats.Length -1){
index = 0;
}
go.renderer.material = mats[index];
}
GUILayout.EndArea();
}
}
If you want to change the other material of the renderer, you can use
go.renderer.materials
http://docs.unity3d.com/Documentation/ScriptReference/Renderer-materials.html?from=MeshRenderer
For example:
go.renderer.materials[0] = mats[0];
go.renderer.materials[1] = mats[1];