Set NickName for photonplayers unity3d - c#

I have a problem seeing the name of the client-side but in my master side names of the player is showing so what I did was like this
public override void OnPlayerEnteredRoom(Player newPlayer)
{
PlayersName();
}
private void PlayersName()
{
if (playerCount == 1)
{
playerNames[0].text = "Kingdom Player 1";
playerNames[1].text = "";
}
else
{
playerNames[0].text = "Kingdom Player 1";
playerNames[1].text = "Kingdom Player 2";
}
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
PlayersName();
}
Now it displays in both sides the problem is that it is not optimize well. Can someone help me, please?

In the photon, you have to check your current room players.
You have too little change in your code. you can't use directly player count. after change, this code is working properly.
public override void OnPlayerEnteredRoom(Player newPlayer)
{
PlayersName();
}
public void PlayersName()
{
if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
{
playerNames[0].text = "Kingdom Player 1";
playerNames[1].text = "";
}
else
{
playerNames[0].text = "Kingdom Player 1";
playerNames[1].text = "Kingdom Player 2";
}
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
PlayersName();
}

Related

PlayerPrefs won't save or load anything when I build the game

I'm trying to make a simple script that saves a text from an input field, like a "remember me" check box. It works fine on the editor. It saves, it logs correctly, it loads fine. But when I build the scene it doesn't work, it's like PlayerPrefs never saves anything. Anyone knows why?
public Toggle rememberMe;
public InputField fieldMail;
public InputField fieldPassword;
private string mail;
private string password;
private int rememberMeChecked = 0;
private bool justChecked = false;
public EventTrigger loginButton;
private void Awake()
{
if (!PlayerPrefs.HasKey("Checked")) { PlayerPrefs.SetInt("Checked", 0); }
if (!PlayerPrefs.HasKey("Mail")) { PlayerPrefs.SetString("Mail", string.Empty); }
if (!PlayerPrefs.HasKey("Password")) { PlayerPrefs.SetString("Password", string.Empty); }
}
private void Start()
{
rememberMeChecked = PlayerPrefs.GetInt("Checked");
mail = PlayerPrefs.GetString("Mail");
password = PlayerPrefs.GetString("Password");
if (!mail.Equals(string.Empty)) { fieldMail.text = mail; }
if (!password.Equals(string.Empty)) { fieldPassword.text = password; }
if (rememberMeChecked == 0) { rememberMe.isOn = false; }
if (rememberMeChecked == 1) { rememberMe.isOn = true; }
justChecked = rememberMe.isOn;
rememberMe.onValueChanged.AddListener(delegate {
justChecked = !justChecked;
if (justChecked) { Save(1); }
else { Save(0); }
LogInfo();
});
}
private void OnEnable()
{
fieldMail.text = mail;
fieldPassword.text = password;
if (rememberMeChecked == 0) { rememberMe.isOn = false; }
if (rememberMeChecked == 1) { rememberMe.isOn = true; }
}
public void OnButtonClicked()
{
PlayerPrefs.Save();
Debug.Log("PlayerPrefs saved.");
LogInfo();
}
public void Save(int rememberMeChecked)
{
switch (rememberMeChecked)
{
case 1:
{
PlayerPrefs.SetString("Mail", fieldMail.text);
PlayerPrefs.SetString("Password", fieldPassword.text);
PlayerPrefs.SetInt("Checked", rememberMeChecked);
}
break;
case 0:
default:
{
PlayerPrefs.SetString("Mail", string.Empty);
PlayerPrefs.SetString("Password", string.Empty);
PlayerPrefs.SetInt("Checked", rememberMeChecked);
}
break;
}
PlayerPrefs.Save();
}

Unsure why logic will not turn game object active

My logic has worked in the past, but it is unclear why this does not work to turn my gameobjects active. This is especially puzzling as I have no errors. The fields match up correctly and I have no errors as mentioned. This is used for an inventory system.
public class addToArtMode : MonoBehaviour
{
public bool On = true;
public GameObject slotPanel;
void Start()
{
this.GetComponent<Button>().onClick.AddListener(() => AddToArtMode());
slotPanel = GameObject.Find("Slot Panel");
}
public void AddToArtMode()
{
if (On)
{
Debug.Log("ID'ing ");
slotPanel = GameObject.Find("Slot Panel");
foreach (Transform child in slotPanel.transform)
{
var parentName = this.GetComponentInParent<ArtBrowseContentInformation>().NameofArt;
var childname = child.GetComponent<InventoryContentInfo>().NameofArt;
if (childname == parentName)
{
child.gameObject.SetActive(true);
On = false;
Debug.Log("what ");
}
else
{
Off();
}
}
void Off()
{
foreach (Transform child in slotPanel.transform)
{
var parentName = this.GetComponentInParent<ArtBrowseContentInformation>().NameofArt;
var childname = child.GetComponent<InventoryContentInfo>().NameofArt;
if (childname == parentName)
{
Debug.Log("the heck");
child.gameObject.SetActive(false);
On = true;
}
}
}
}
}
}
}
try gameObject.enabled = false/true;

Anchoring in Vuforia

I'm able to fix the position of the object once it's spawned. But, the object is placed onto different position on every tap on the screen. I want to avoid this problem and want my object to be fixed in a spawned position throughout the Session or Application lifetime.
This is my Deploy Stage Once script:
public class DeployStageOnce : MonoBehaviour
{
public GameObject AnchorStage;
private PositionalDeviceTracker _deviceTracker;
private GameObject _anchorGameObject;
private GameObject _previousAnchor;
public void Start()
{
if (AnchorStage == null)
{
Debug.Log("AnchorStage must be specified");
return;
}
AnchorStage.SetActive(false);
}
public void Awake()
{
VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
}
public void OnDestroy()
{
VuforiaARController.Instance.UnregisterVuforiaStartedCallback(OnVuforiaStarted);
}
private void OnVuforiaStarted()
{
_deviceTracker = TrackerManager.Instance.GetTracker<PositionalDeviceTracker>();
}
private void AnchorGameObjectSetHitTestPosition(HitTestResult reuslt)
{
_anchorGameObject.transform.position = reuslt.Position;
_anchorGameObject.transform.rotation = reuslt.Rotation;
}
public void OnInteractiveHitTest(HitTestResult result)
{
if (result == null || AnchorStage == null)
{
Debug.LogWarning("Hit test is invalid or AnchorStage not set");
return;
}
var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
_anchorGameObject = new GameObject();
AnchorGameObjectSetHitTestPosition(result);
if (anchor != null)
{
AnchorStage.transform.parent = _anchorGameObject.transform;
AnchorStage.transform.localPosition = Vector3.zero;
AnchorStage.transform.localRotation = Quaternion.identity;
AnchorStage.SetActive(true);
}
if (_previousAnchor != null)
{
Destroy(_previousAnchor);
}
_previousAnchor = _anchorGameObject;
}
}
Well you can create an isPlaced variable in your script to check if your object is already placed like this:
private bool isPlaced = false;
public void OnInteractiveHitTest(HitTestResult result)
{
if (result == null || AnchorStage == null)
{
Debug.LogWarning("Hit test is invalid or AnchorStage not set");
return;
}
if(!isPlaced)
{
var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
_anchorGameObject = new GameObject();
AnchorGameObjectSetHitTestPosition(result);
if (anchor != null)
{
AnchorStage.transform.parent = _anchorGameObject.transform;
AnchorStage.transform.localPosition = Vector3.zero;
AnchorStage.transform.localRotation = Quaternion.identity;
AnchorStage.SetActive(true);
}
isPlaced = true;
}
}

Class for controlling properties of the PictureBox (C# forms)

I am trying to write something along of a "clean" code... I want to make a Pong game, for now based on Forms.
I want to divide the game nicely into classes.
I want to have a ball class, AI that inherits from player class, I want to use the premade Form class for setting main Form properties (width etc).
I made a player class as such and I would like to ask you if the approach for naming, getters and setters and the general idea is correct. Isn't certain bits (if not all of it) rather redundant or badly written, I do not want to base entire "project" on bad assumptions and multiply the same mistakes all over the code.
namespace Pong
{
public class Player
{
protected PictureBox PaddleBox { get; set; }
protected Size PlayerSize
{
get
{
return PlayerSize;
}
set
{
if (PlayerSize.Height > 0 && PlayerSize.Width > 0)
{
PlayerSize = new Size(value.Width, value.Height);
PaddleBox.Size = PlayerSize;
}
}
}
protected Point Location
{
get
{
return Location;
}
set
{
PaddleBox.Location = new Point(value.X, value.Y);
}
}
protected Color BackColor
{
get
{
return BackColor;
}
set
{
PaddleBox.BackColor = value;
}
}
public Player()
{
PaddleBox = new PictureBox();
}
}
}
FORM class looks something along of this for now, maybe I should pass parameters such as size,location and color in the constructor? What is the best?
namespace Pong
{
public partial class Form1 : Form
{
public Timer gameTime;
const int screenWidth = 1248;
const int screenHeight = 720;
public Form1()
{
InitializeComponent();
this.Height= screenHeight;
this.Width=screenWidth;
this.StartPosition=FormStartPosition.CenterScreen;
Player player = new Player();
player.PaddleBox.Size = new Size(20, 50);
player.PaddleBox.Location = new Point(player.PaddleBox.Width / 2, ClientSize.Height/2-player.PaddleBox.Height/2);
player.PaddleBox.BackColor = Color.Blue;
this.Controls.Add(player.PaddleBox);
gameTime = new Timer();
gameTime.Enabled = true;
}
void gameTime_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You got an issue here:
protected Point Location
{
get
{
return Location; // <--- this is a circular reference..
// meaning, it will recall this getter again.
}
set
{
PaddleBox.Location = new Point(value.X, value.Y);
}
}
use this instead:
protected Point Location
{
get
{
return PaddleBox.Location;
}
set
{
PaddleBox.Location = value;
}
}
Same with protected Color BackColor
Here is an example, how I would implement it (in your current programming style (powered by notepad))
namespace Pong
{
public partial class Form1 : Form
{
public Timer gameTime;
const int screenWidth = 1248;
const int screenHeight = 720;
public Form1()
{
InitializeComponent();
this.Height= screenHeight;
this.Width=screenWidth;
this.StartPosition=FormStartPosition.CenterScreen;
Player player = new Player(this);
player.PlayerSize = new Size(20, 50);
player.Location = new Point(player.PaddleBox.Width / 2, ClientSize.Height/2-player.PaddleBox.Height/2); // <-- the location is always the upperleft point. don't do this...
player.BackColor = Color.Blue;
gameTime = new Timer();
gameTime.Enabled = true;
}
private void gameTime_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class Player
{
private PictureBox _paddleBox;
protected Size PlayerSize
{
get
{
return _paddleBox.Size;
}
set
{
if (PlayerSize.Height == 0 || PlayerSize.Width == 0)
throw new ArgumentException("Size must be greater than 0");
_paddleBox.Size = value;
}
}
protected Point Location
{
get { return PaddleBox.Location; }
set { PaddleBox.Location = value; }
}
protected Color BackColor
{
get { return PaddleBox.BackColor; }
set { PaddleBox.BackColor = value; }
}
public Player(Form form)
{
PaddleBox = new PictureBox();
form.Controls.Add(PaddleBox);
}
}
}
You should try to isolate the picturebox in your player class, this will separate the functionality of the form and the picturebox...

Replace TextBox with int

I have the following, and it works:
My player class:
public Player(string Str, string SP)
{
Strength = Str;
StatPoints = SP;
}
public string StatPoints
{
get;
set;
}
public string Strength
{
get;
set;
}
Now on my form1 I have a textbox, and a button. The button increments the value in the textbox by one so long as there is a value above 0 in the SP textbox. Problem is, I am declaring six variables in order to manage two values because I have to convert strings to ints and all that crap. Is there a way to replace text boxes with something that is inherently int? Here is my character sheet code so far.
private void AddButton_Click(object sender, EventArgs e)
{
Player PCStats = new Player(StrBox.Text, SPBox.Text);
int IntPCSP = Convert.ToInt16(PCStats.StatPoints);
int IntPCStr = Convert.ToInt16(PCStats.Strength);
if (IntPCSP >= 1 && IntPCStr <= 7)
{
IntPCStr++;
IntPCSP--;
PCStats.Strength = IntPCStr.ToString();
PCStats.StatPoints = IntPCSP.ToString();
StrBox.Text = PCStats.Strength;
SPBox.Text = PCStats.StatPoints;
}
else
{
MessageBox.Show("Earn more experience!");
}
/*
MessageBox.Show("PCStats.StatPoints equals" + PCStats.StatPoints);
MessageBox.Show("PCStats,Strength equals" + PCStats.Strength);
MessageBox.Show("IntPCSP Equals" + IntPCSP.ToString());
MessageBox.Show("IntPCStr Equals" + IntPCStr.ToString());
*/
}
Or is there an even easier way to do this I completely overlooked. I was super excited to finally get this bit to work after a lot of trial and error, but I am open to redoing it. I would rather however just replace the text boxes so I am not converting variables all over the place.
This is quick go, not at a computer with Visual Studio on it but should give you a start. Also, try naming your variables etc to have a bit more meaning. Also, this is to fix what you has as-is but see my update / suggestion further down about moving logic into the Player class...
My player class:
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
public int StatPoints { get; set; }
public int Strength { get; set; }
My Form:
private void AddButton_Click(object sender, EventArgs e)
{
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.StatPoints > 0 && thePlayer.Strength < 8)
{
thePlayer.Strength++;
thePlayer.StatPoints--;
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
Obviously you would need to check that the values in the text box were integers. You could use another control, mask the text box etc or on the code replace int.Parse with int.TryParse which checks it is possible before conversion. Just a few ideas to get you going!
- UPDATE -
Another thing you could do is more the logic into the Player class. This is better as it keep the logic contained in one place so you can see what a Player can DO rather than having to search the whole program:
New Player class:
// The Player class
public class Player
{
// Constructor
public Player(int strength, int statPoints)
{
this.Strength = strength;
this.StatPoints = statPoints;
}
// Method to gain strength if enough StatPoints
public bool GainStrength()
{
bool playerHasEnoughStatPoints = true;
if (this.StatPoints < 1)
{
playerHasEnoughStatPoints = false;
}
else if (this.Strength < 8)
{
this.Strength++;
this.StatPoints--;
}
return playerHasEnoughStatPoints;
}
// Property for StatPoints
public int StatPoints { get; set; }
// Property for Strength
public int Strength { get; set; }
}
New Form:
// The Form or similar
public class MyFormOrSimilar
{
// When button pressed try and add strength to the player
protected void AddButton_Click(object sender, EventArgs e)
{
// Create new INSTANCE of the player and try to give them strength
Player thePlayer = new Player(int.Parse(StrBox.Text), int.Parse(SPBox.Text));
if (thePlayer.GainStrength())
{
StrBox.Text = thePlayer.Strength.ToString();
SPBox.Text = thePlayer.StatPoints.ToString();
}
else
{
MessageBox.Show("Earn more experience!");
}
}
}

Categories

Resources