SetValue赋值一般变量直接使用,但是struct需要装箱成object再进行就可以了. 不知道行不行
using UnityEngine;
using System.Collections;
using TeamUtility.IO;
using System.Reflection;
using System;
namespace HS.Thinbug.CharControl
{
/// <summary>
/// User input for a third person character controller.
/// </summary>
public class TBUserControlThird : MonoBehaviour {
// Input state
public struct State {
public Vector3 move;
public Vector3 lookPos;
public bool crouch;
public bool jump;
public int actionIndex;
}
class StateClass
{
public State val;
}
public bool walkByDefault; // toggle for walking state
public bool canCrouch = true;
public bool canJump = true;
public State state = new State(); // The current state of the user input
public State stateLast = new State(); // The current state of the user input
protected Transform cam; // A reference to the main camera in the scenes transform
GamePlayer hero;
void Start () {
// get the transform of the main camera
cam = Camera.main.transform;
}
public void InitControl(GamePlayer h)
{
hero = h;
}
public void SAGet(ArrayList parm)
{
int fieldType = (int)parm[0];
string field = (string)parm[1];
object data;
//state. [field] = (object)parm[1];
switch (fieldType)
{
case 0://如果是bool,那么需要转换下
data = (int)parm[2] == 1 ? true : false;
break;
case 1://如果是小数,那么要缩小
data = (int)parm[2] * 0.01f;
break;
default:
data = parm[2];
break;
}
object ob = state;
FieldInfo fi2 = state.GetType().GetField(field);
fi2.SetValue(ob, data);
state = (State)ob;
}
void checkSendSA()
{
if (stateLast.jump != state.jump)
{
stateLast.jump = state.jump;
SA(new ArrayList() { new ArrayList() { 0, "jump", stateLast.jump ? 1 : 0 }, 1 });
}
if (stateLast.crouch != state.crouch)
{
stateLast.crouch = state.crouch;
SA(new ArrayList() { new ArrayList() { 0, "crouch", stateLast.crouch ? 1 : 0 }, 1 });
}
}
protected virtual void Update () {
// read inputs
state.crouch = canCrouch && InputManager.GetAxisRaw("stun") > 0 ? true : false; //Input.GetKey(KeyCode.C);
state.jump = canJump && (int)InputManager.GetAxisRaw("Jump")> 0? true :false;// ..GetButton("Jump");
checkSendSA();
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
// calculate move direction
Vector3 fwd = new Vector3(cam.forward.x, 0f, cam.forward.z).normalized;
if(fwd != Vector3.zero)
state.move = Quaternion.LookRotation(fwd) * new Vector3(h, 0f, v);//.normalized;
bool walkToggle = Input.GetKey(KeyCode.LeftShift);
// We select appropriate speed based on whether we're walking by default, and whether the walk/run toggle button is pressed:
float walkMultiplier = (walkByDefault ? walkToggle ? 1 : 0.5f : walkToggle ? 0.5f : 1);
state.move *= walkMultiplier;
// calculate the head look target position
state.lookPos = transform.position + cam.forward * 100f;
}
public void SA(ArrayList parm)
{
((HeroPlayer)hero).TosFun("SA", parm);
}
}
}