I'm trying to trigger the transition from an idle animation to a running animation when the "d" button is being pressed.
(A link to a tutorial covering a transition like this could also work).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdleToJump : MonoBehaviour
{
bool keyHold = false;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (keyHold == true)
{
anim.Play("Run_Anim");
}
}
private void Key_up(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == "d") {
keyHold = false;
}
}
private void Key_down(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == "d")
{
keyHold = true;
}
}
}
Cross-check, you're code with this.
Form1 looks like a constructor that somehow got autogenerated. Just comment it out, and add the last two methods inside the class not outside.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdleToJump : MonoBehaviour
{
bool keyHold = false;
//public Form1()//Not sure this constructor is relevant in class, so just comment it
//{
//InitializeComponent();
//}
private void timer1_Tick(object sender, EventArgs e)
{
if (keyHold == true)
{
anim.Play("Run_Anim");
}
private void Key_up(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == "d") {
keyHold = false;
}
}
private void Key_down(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == "d")
{
keyHold = true;
}
}
}
}
Related
I'm trying to sync all the player names on server and client side, I'm following this tutorial, but I've made some changes to the code.
InitiateMultiplayer.cs
using Unity.Netcode;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Text;
namespace Multiplayer
{
public class InitiateMultiplayer : MonoBehaviour
{
[Serializable]
public class ConnectionPayload
{
public string password;
public string playerName;
}
public struct PlayerData
{
public string PlayerName { get; private set; }
public PlayerData(string playerName)
{
PlayerName = playerName;
}
}
private static Dictionary<ulong, PlayerData> clientData;
// Start is called before the first frame update
void Start()
{
NetworkManager.Singleton.NetworkConfig.ConnectionApproval = true;
switch (Buttons.GameMode)
{
case "Host":
clientData = new Dictionary<ulong, PlayerData>();
clientData[NetworkManager.Singleton.LocalClientId] = new PlayerData(Buttons.PlayerName);
NetworkManager.Singleton.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.Singleton.StartHost();
break;
case "Client":
Debug.Log("Client Started");
var payload = JsonUtility.ToJson(new ConnectionPayload()
{
password = "",
playerName = Buttons.PlayerName,
});
byte[] payloadBytes = Encoding.ASCII.GetBytes(payload);
// Set password ready to send to the server to validate
NetworkManager.Singleton.NetworkConfig.ConnectionData = payloadBytes;
NetworkManager.Singleton.StartClient();
break;
default:
break;
}
}
public static PlayerData? GetPlayerData(ulong clientId)
{
if (clientData.TryGetValue(clientId, out PlayerData playerData))
{
return playerData;
}
return null;
}
private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
Debug.Log("approving");
string payload = Encoding.ASCII.GetString(request.Payload);
var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload);
response.Approved = true;
response.Position = Vector3.zero;
response.Rotation = Quaternion.identity;
if (response.Approved)
{
response.CreatePlayerObject = true;
Debug.Log("approved");
response.PlayerPrefabHash = null;
response.Pending = false;
if (!clientData.TryGetValue(request.ClientNetworkId, out PlayerData playerData)) {
Debug.Log("we dont got data");
clientData[request.ClientNetworkId] = new PlayerData(connectionPayload.playerName);
}
}
}
}
}
Player.cs
using Unity.Netcode;
using UnityEngine;
using TMPro;
using Unity.Collections;
namespace Multiplayer
{
public class Player : NetworkBehaviour
{
[SerializeField] private TMP_Text displayNameText;
[SerializeField] private Renderer playerBody3D;
private NetworkVariable<FixedString32Bytes> displayName = new NetworkVariable<FixedString32Bytes>();
public override void OnNetworkSpawn()
{
if (!IsServer) { return; }
Debug.Log("Sapwned");
InitiateMultiplayer.PlayerData? playerData = InitiateMultiplayer.GetPlayerData(OwnerClientId);
if (playerData.HasValue)
{
Debug.Log("data -"+playerData.Value.PlayerName);
displayName.Value = playerData.Value.PlayerName;
}
}
private void OnEnable()
{
displayName.OnValueChanged += HandleDisplayNameChanged;
}
private void OnDisable()
{
displayName.OnValueChanged -= HandleDisplayNameChanged;
}
private void HandleDisplayNameChanged(FixedString32Bytes oldDisplayName, FixedString32Bytes newDisplayName)
{
if (IsClient) Debug.Log("client");
Debug.Log("Change in value"+newDisplayName.ToString());
displayNameText.text = newDisplayName.ToString();
}
}
}
The issue I'm facing is that the names are getting synced only on the server side, on the client side the palyer names are the default text.
I have been stuck on this problem for a few months now. The problem being that I cannot properly instantiate my prefabs in the scene I want. I need the spawning to be one person on one team, and the rest on the other. But I'm not sure how to do that. What happens is that when I click the play button on my lobby menu, I get an error called "No cameras to display." I also noticed that the scene I want does load, but it doesn't switch to it because there are no cameras that are instantiated. I am using Photon 2. I am new to game development and your guys' help would be greatly appreciated! :)
I will post my code if that will help:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;
using Photon.Realtime;
using System.Linq;
using System.IO;
public class Launcher : MonoBehaviourPunCallbacks
{
public static Launcher Instance;
[SerializeField] TMP_InputField roomNameInputField;
[SerializeField] TMP_Text errorText;
[SerializeField] TMP_Text RoomNameText;
[SerializeField] Transform RoomListBackground;
[SerializeField] Transform PlayerListBackground;
[SerializeField] GameObject roomListItem_pf;
[SerializeField] GameObject PlayerListItem_pf;
[SerializeField] GameObject startGameButton;
public PhotonView PV;
public int myTeam;
public GameObject myAvatar;
void Awake()
{
Instance = this;
}
void Start()
{
Debug.Log("Connecting to Master");
PhotonNetwork.ConnectUsingSettings();
}
public void Update()
{
PV = GetComponent<PhotonView>();
if (PV)
{
PV.RPC("RPC_GetTeam", RpcTarget.MasterClient);
}
if (myAvatar == null && myTeam != 0)
{
if (myTeam == 1)
{
if (PV.IsMine)
{
int spawnPicker = Random.Range(0, GameSetup.GS.spawnPointsTeamOne.Length);
myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameSetup.GS.spawnPointsTeamOne[spawnPicker].position, GameSetup.GS.spawnPointsTeamOne[spawnPicker].rotation, 0);
}
}
if (myTeam == 2)
{
if (PV.IsMine)
{
int spawnPicker = Random.Range(0, GameSetup.GS.spawnPointsTeamTwo.Length);
myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameSetup.GS.spawnPointsTeamTwo[spawnPicker].position, GameSetup.GS.spawnPointsTeamTwo[spawnPicker].rotation, 0);
}
}
}
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to Master");
PhotonNetwork.JoinLobby();
PhotonNetwork.AutomaticallySyncScene = true;
}
public override void OnJoinedLobby()
{
MenuManager.Instance.OpenMenu("title");
Debug.Log("Joined Lobby");
}
public void CreateRoom()
{
if (string.IsNullOrEmpty(roomNameInputField.text))
{
return;
}
PhotonNetwork.CreateRoom(roomNameInputField.text);
MenuManager.Instance.OpenMenu("loading");
}
public override void OnJoinedRoom()
{
MenuManager.Instance.OpenMenu("room");
RoomNameText.text = PhotonNetwork.CurrentRoom.Name;
Player[] players = PhotonNetwork.PlayerList;
for (int i = 0; i < players.Count(); i++)
{
Instantiate(PlayerListItem_pf, PlayerListBackground).GetComponent<PlayerListItem>().Setup(players);
}
startGameButton.SetActive(PhotonNetwork.IsMasterClient);
}
public override void OnMasterClientSwitched(Player newMasterClient)
{
startGameButton.SetActive(PhotonNetwork.IsMasterClient);
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
errorText.text = "Room Creation Failed: " + message;
MenuManager.Instance.OpenMenu("error");
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
MenuManager.Instance.OpenMenu("loading");
}
public void JoinRoom(RoomInfo info)
{
PhotonNetwork.JoinRoom(info.Name);
MenuManager.Instance.OpenMenu("loading");
}
public override void OnLeftRoom()
{
MenuManager.Instance.OpenMenu("title");
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
foreach (Transform trans in RoomListBackground)
{
Destroy(trans.gameObject);
}
for (int i = 0; i < roomList.Count; i++)
{
Instantiate(roomListItem_pf, RoomListBackground).GetComponent<RoomListItem>().Setup(roomList);
}
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Instantiate(PlayerListItem_pf, PlayerListBackground).GetComponent<PlayerListItem>().Setup(newPlayer);
}
[PunRPC]
public void RPC_GetTeam()
{
myTeam = GameSetup.GS.nextPlayersTeam;
GameSetup.GS.UpdateTeam();
PV.RPC("RPC_SentTeam", RpcTarget.OthersBuffered, myTeam);
}
[PunRPC]
public void RPC_SentTeam(int whichTeam)
{
myTeam = whichTeam;
}
}
I am trying to make simple app and got stuck. User chooses start date from date picker1 28.01.2015 and end date picker2 29.01.2015 then marks what he/she wants via checkboxes and presses button. The output in console should look similar to this depending on what is marked.
tar zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log`
but instead date picked as start date is returned twice in console and I have no idea what is wrong:
zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log
Code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
using System.Configuration;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
}
...
private void button1_Click(object sender, EventArgs e)
{
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
GlobalMethods dateIterator = new GlobalMethods();
dateIterator.Iterator();
GlobalVariables.comminit = null;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
GlobalVariables.cLM = true;
}
else if (!checkBox1.Checked)
{
GlobalVariables.cLM = false;
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateStart = dateTimePicker1.Value;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateEnd = dateTimePicker2.Value;
//string endDate = dateTimePicker2.Value.ToString("yyyyMMdd");
}
}
public static class GlobalVariables
{
// Log variables below
public static Boolean mLM;
public static Boolean cLM;
public static Boolean hLM;
public static Boolean pLM;
public static Boolean prLM;
public static Boolean compressMarked = true;
public static String iterate;
public static String comminit;
public static String pH;
public static String pP;
public static String pC;
public static String ppP;
public static String pM;
// Time variables below
public static DateTime dateStart = DateTime.Now;
public static DateTime dateEnd = DateTime.Now;
}
public class Instructions
{
public static String hLl()
{
if (GlobalVariables.compressMarked)
{
return "tar zxcvf " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;";
}
else { return "wget " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;"; }
}
...
public static String commandsBath()
{
if (GlobalVariables.mLM == true)
{
GlobalVariables.comminit += mLl();
}
if (GlobalVariables.cLM == true)
{
GlobalVariables.comminit += cLl();
}
if (GlobalVariables.hLM == true)
{
GlobalVariables.comminit += hLl();
}
if (GlobalVariables.pLM == true)
{
GlobalVariables.comminit += pLl();
}
if (GlobalVariables.prLM == true)
{
GlobalVariables.comminit += pLlp();
}
return GlobalVariables.comminit;
}
}
public class GlobalMethods
{
public void Iterator()
{
for (DateTime i = GlobalVariables.dateStart; i <= GlobalVariables.dateEnd; i = i.AddDays(1))
{
string iterated = i.ToString("yyyyMMdd");
GlobalVariables.iterate = iterated;
}
}
public void ConfigRead()
{
...
}
public void ConfigWrite()
{
...
}
}
}
Hopefully someone can help.
Never mind, found the solution. Instead of using += and add results of if statements it is better to use String builder like below. This way it works correctly and is more simple.
var sb = new StringBuilder();
if (GlobalVariables.mLM == true) sb.Append(mLl());
if (GlobalVariables.cLM == true) sb.Append(cLl());
...
return GlobalVariables.comminit = sb.ToString();
I am having a model not in EF, but in plain text. I have to have the updated events handled for each of the model's properties so that i can log their changes.
Is there a way for this to be achieved.
Implement the INotifyPropertyChanged interface.
A simple example:
using System.ComponentModel;
public class MyModel : INotifyPropertyChanged
{
string _myProperty;
public event PropertyChangedEventHandler PropertyChanged;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
public void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
You can use it like...
public class Test
{
public static void Main()
{
var model = new MyModel();
model.PropertyChanged += new PropertyChangedEventHandler(LogChange);
model.MyProperty="apples";
model.MyProperty="oranges";
model.MyProperty="pears";
}
public static void LogChange(object sender, PropertyChangedEventArgs args)
{
Console.WriteLine(args.PropertyName + " has changed!");
Console.WriteLine("New value: "
+ sender.GetType().GetProperty(args.PropertyName)
.GetValue(sender, null));
}
}
I'm having trouble on adding a UserControl to my Form.
UserControl Code:
using System;
using System.Windows.Forms;
namespace Most.Mobile.AFV.UI.Controls
{
public partial class ListActionBar : UserControl
{
public ListActionBar()
{
InitializeComponent();
}
public bool ShowKeyboardButton
{
get { return mtbKeyboard.Visible; }
set { mtbKeyboard.Visible = value; }
}
public bool ShowOpenButton
{
get { return mtbMenu.Visible; }
set { mtbMenu.Visible = value; }
}
public bool ShowDeleteButton
{
get { return mtbDelete.Visible; }
set { mtbDelete.Visible = value; }
}
public bool ShowBackButton
{
get { return mtbBack.Visible; }
set { mtbBack.Visible = value; }
}
public bool ShowEditButton
{
get { return mtbEdit.Visible; }
set { mtbEdit.Visible = value; }
}
public bool ShowNewButton
{
get { return mtbNew.Visible; }
set { mtbNew.Visible = value; }
}
public event EventHandler NewClick;
public event EventHandler DeleteClick;
public event EventHandler EditClick;
public event EventHandler OpenClick;
private void mtbBack_Click(object sender, EventArgs e)
{
if (Parent == null)
return;
if (Parent is Form)
(Parent as Form).DialogResult = DialogResult.Cancel;
}
private void mtbKeyboard_Click(object sender, EventArgs e)
{
inp.Enabled = !inp.Enabled;
}
private void mtbNew_Click(object sender, EventArgs e)
{
if (NewClick != null)
NewClick(sender, e);
}
private void mtbEdit_Click(object sender, EventArgs e)
{
if (EditClick != null)
EditClick(sender, e);
}
private void mtbDelete_Click(object sender, EventArgs e)
{
if (DeleteClick != null)
DeleteClick(sender, e);
}
private void mtbMenu_Click(object sender, EventArgs e)
{
if (OpenClick != null)
OpenClick(sender, e);
}
}
}
Below a picture of the error
Error description:
Failed to create component ''
'System.IO.FileLoadException:Could not load file or assembly 'Microsoft.WindowsCE.Forms, Version=3.5.0.0, CUlture=neutral, PublicKeyToken=969db8053d3322ac' or one of its dependencies.
The visual studio designer instantiates the control when displaying it in the designer view. when you get errors like this it normally means you have a runtime bug. if it compiles, try running the code (without opening it up in designer) and see where/if it crashes.