I’m making a shooter game and want to make my character hold weapons by changing the targets for hand TwoBoneIKConstraints throught script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using Bolt;
public class WeaponManagerScript : MonoBehaviour
{
public GameObject[] slots;
public Rig handRig;
public TwoBoneIKConstraint rightHand;
public TwoBoneIKConstraint leftHand;
int held = 0;
void Start()
{
//rightHand = handRig.transform.Find("RightHandConst").GetComponent<TwoBoneIKConstraint>();
//leftHand = handRig.transform.Find("LeftHandConst").GetComponent<TwoBoneIKConstraint>();
SwitchWeapon(0, 0);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1)) SwitchWeapon(held, 0);
else if (Input.GetKeyDown(KeyCode.Alpha2)) SwitchWeapon(held, 1);
else if (Input.GetKeyDown(KeyCode.Alpha3)) SwitchWeapon(held, 2);
else if (Input.GetKeyDown(KeyCode.Alpha4)) SwitchWeapon(held, 3);
}
void SwitchWeapon(int current, int target)
{
held = target;
Debug.Log("Switching from " + current + " to " + target);
foreach(var obj in slots)
{
WeaponScript wep = obj.GetComponentInChildren<WeaponScript>();
if(wep) wep.enabled = false;
}
WeaponScript awep = slots[target].GetComponentInChildren<WeaponScript>();
if (awep) awep.enabled = true;
Transform newRightHand = null;
Transform newLeftHand = null;
try
{
newRightHand = awep.transform.Find("RightGrip").transform;
}
catch
{
}
try
{
newLeftHand = awep.transform.Find("LeftGrip").transform;
}
catch
{
}
if (newRightHand != null)
{
rightHand.data.target = newRightHand;
rightHand.weight = 1f;
}
else
{
Debug.Log("No right grip!");
rightHand.weight = 0f;
}
if (newLeftHand != null)
{
leftHand.data.target = newLeftHand;
leftHand.weight = 1f;
}
else
{
leftHand.weight = 0f;
}
}
}
The problem is this doesn’t work (target and weight doesn’t get changed) unless I disable and re-enable RigBuilder compoenent in the editor when the game is already running (doing the same through script doesnt help). Can someone please help me fix this issue?