Trying to access variables from another script in unity (Not Homework) - unity3d

I am currently playing around in Unity trying to make/test a 2D game. I keep getting the following error when I attempt to access CharacterMotor.playerx from inside camerafollow.js:
An instance of type "CharacterMotor" is required to access non static member "playerx"
Here are my two scripts:
camerafollow.js
#pragma strict
function Start () {
transform.position.x = CharacterMotor.playerx;
}
CharacterMotor.js
#pragma strict
#pragma implicit
#pragma downcast
public var playerx : float = transform.position.x;

You could change playerx to static, but I don't think that's what you want to do (there's probably only one player object, but this would prevent you from ever having multiple CharacterMotors). I think you want/need to retrieve the instance of CharacterMotor that is attached to this gameObject.
#pragma strict
function Start () {
var charMotor : CharacterMotor = gameObject.GetComponent(CharacterMotor);
transform.position.x = charMotor.playerx;
}

An instance of type "CharacterMotor" is required to access non static member "playerx"
The above error message describes precisely what is happening. You are just trying to access a variable without first creating an instance of it. Keep in mind that UnityScript != JavaScript.
To fix this issue, simply change
public var playerx : float = transform.position.x;
to
public static var playerx : float = transform.position.x;
Though this fixes your immediate problem I do not recommend continuing down this path. I suggest that you learn other aspects of the language first (such as classes) so that you can better organize and construct your data.
See: http://forum.unity3d.com/threads/34015-Newbie-guide-to-Unity-Javascript-(long)

CharacterMotor is the type, there can be multiple instantiations of your type in memory at the same time so when you call the type name you are not referencing any instance in memory.
to get an instance of the type that is connected to you current gameobject try this:
var charactorMotor : CharacterMotor = gameObject.getComponent("CharacterMotor");
Now you have access to that instances properties
transform.position.x = characterMotor.playerx;

Related

unused assigned variables in Unity character skeleton mapping

I have a motion-capture system that I use to animate a character (non-mecanim) so obviously I have to map the motion data onto the character's bones and segments.
Here is how I do it, but since the joints names are only used within the mapBones() method, I get quite a few amber warnings at the Unity console that warning CS0219: The variable JtHips is assigned but its value is never used.
I get one for each bone! It does not look professional, so I am wondering if there is any way I could get rid of them? All the posts I have checked out, of course recommend using them, but in this case, they are being used internally by the mapping function...
private Dictionary<MoCapSegment, ChrBones> jointsDict;
public enum MoCapSegment
{
Pelvis = 0,
// many more ...
Neck = 48,
Head = 49
}
public enum ChrBones
{
JtHips = 0,
// many more ...
JtNeckA = 48,
JtSkullA = 49
}
protected void mapBones()
{
jointsDict = new Dictionary<MoCapSegment, ChrBones>();
GameObject JtHips = transform.Find("CharacterRoot/JtJtHips").gameObject;
jointsDict.Add(MoCapSegment.Pelvis, ChrBones.JtHips);
// all the rest
}
You CAN do the following, but be careful
#pragma warning disable 0414
Specifically,
#pragma warning disable 0168// variable declared but not used.
#pragma warning disable 0219// variable assigned but not used.
#pragma warning disable 0414// private field assigned but not used.
I agree with you that this problem is infuriating.
Another thing you can do is this...
public void check<T>(T x){}
and then you can
private Whatever JtHips = whatever; // throws warning since never used
check(JtHips); // avoid warning like this
As always it's a great chance to use an extension
public static class YourExtensions
{
public static void Nothing<T>(this T x) {}
and then you can
JtHips.Nothing();
JtNeck.Nothing();
JtSkull.Nothing();
etc...
All that being said, it's a very bad idea to suppress warnings, of course. Take care.

Assigning script to a variable with a variable (Unity 3D)

So the title is a bit weird but i didnt know how to call it.
I am working on a FPS game and I am trying to make a simple weaponsystem. Every Player can have a primary and a secondary weapon. I am at the moment trying to write a script to change between the assigned primary/secondary weapons.
So at first I am doing this:
var primary : GameObject;
var secondary : GameObject;
So I have some GUI Buttons that when they get clicked they assign the desired weapon to the variables primary/secondary.
An code example:
function assignump45() {
primary = ump;
}
Now I want to write a function to switch between the primary and secondary weapon.
So I tried this:
function switchtoprimary(){
if(Input.GetKeyDown("2")){
primary.inv(); //makes the primary weapon invisible
secondary.vis(); //makes the primary weapon visible
}
}
Of course I get this error:
BCE0019: 'inv' is not a member of 'UnityEngine.GameObject'.
I know that what I wrote is wrong. So I tried to get the script of the primary/secondary weapons so I can disable/activate them:
var primscipt : umpscript = GameObject.Find(ump).GetComponent(umpscript);
This works BUT I can´t write for every weapon this kind of script because I then I need to write several combinations of switching between the weapons and that isn´t possible because i know there is a better solution..
I can´t do a if clause and then assign the primscript because the variable only would be assigned in the if clause..
What I need is something like this (doesn´t work of course^^).
var primscipt : primaryscriptstring = GameObject.Find(primarystring).GetComponent(primaryscriptstring);
So I could assign the variable primaryscriptstring with "umpscript" for example. the variable primarystring does work in this case
Are there any workarounds? I am pretty desperate at the moment :/
You'll probably want to create a Weapon class, and have your primary and secondary vars be Weapons, not GameObjects.
var primary : Weapon;
var secondary : Weapon;
Your Weapon.js file might look something like:
function vis () {
...
}
function inv () {
...
}
Then assuming you want to have every weapon type be an extended class of Weapon, you might create a UMP.js file for example and have its class extend Weapon like so:
#pragma strict
class UMP extends Weapon {
}
UMP then inherits all functions and vars from the Weapon class. So then, elsewhere in your code, the following line would work (assuming there's a GameObject named "UMP" somewhere that has the UMP component attached):
function assignump45() {
var ump : UMP = GameObject.Find("UMP").GetComponent(UMP);
primary = ump;
primary.vis();
}
Alternatively, you might not want to have every weapon type be an extended class, and just have one Weapon class for all weapons, in which case you wouldn't create a UMP.js file, and instead your code might look like:
function assignump45() {
var ump : Weapon = GameObject.Find("UMP").GetComponent(Weapon);
primary = ump;
primary.vis();
}
Instead of
primary.inv();
secondary.vis();
do
primary.SetActive(false);
secondary.SetActive(true);
The SetActive method works for any game object, so you don't have to worry about the specific type of weapon or script. See the Unity docs on this here.

How can I properly create invalid Vector3 in Unity?

I often need to pass invalid location to functions that optionally can use location (eg. RTS unit action). But this does not compile:
public abstract void CastSpell(Spell spell, Vector3 targetLocation = null);
So how can I make a proper invaid Vector3 to determine invalid/"don't care" locations? I've seen things like vector with -999999 coordinates - but that's a nasty trick that might cause bugs (eg. on huge maps).
I had a similar problem in the past, I found there was two solutions. The first solution was to create a wrapper for the class.
Class Vector3Wrapper
{
Vector3 vector;
}
Then I would simply set the Vector3Wrapper to null then if it wasnt null access its vector. A better method would be making it a Nullable type. A example is below.
http://unitypatterns.com/nullable-types/
public class Character : MonoBehaviour
{
//Notice the added "?"
Vector3? targetPosition;
void MoveTowardsTargetPosition()
{
//First, check if the variable has been assigned a value
if (targetPosition.HasValue)
{
//move towards targetPosition.Value
}
else
{
//targetPosition.Value is invalid! Don't use it!
}
}

Walker boys tutorial... NullPointerException error

I am seeing the Walker boys tutorial, Im on the Project #2, where you make a ship that destroys asteroids... and there's a part where the bullet must call a function from other object... (here's the video http://vimeo.com/19463502) I do everything that is here but I get this error:
"NullReferenceException: Object reference not set to an instance of an object
scriptBullet.OnTriggerEnter (UnityEngine.Collider other) (at Assets/scriptBullet.js:39)
and that line of code is :
sceneManager.transform.GetComponent(scriptsceneManager).AddScore();
scriptsceneManager.js
var gameTime : float = 60;
static var score : int = 0;
function Update ()
{
print("score : " +score);
}
public function AddScore()
{
score +=1;
}
From what i can see (it's been a while since i did the walkerboy tutorials) there are only 2 reason why you can get a NullPointerException here.
The SceneManager has not been initialised in scriptBullet.js. If you are finding the GameObject by Tag make sure you have the tag assigned and is spelled correctly in the script. I always forget to assign tags until it's no late.
The scriptsceneManager hasn't been added to the SceneManager object. This results in the GetComponent call returning null.
If you are using Monodevelop, remember if you hit the attach button, you can attach UnityEditor to monodevelop, then you can use breakpoints to find out where the NullPointer is coming from.
https://docs.unity3d.com/Documentation/Manual/Debugger.html
Hope this helps.

Unity3D. How to construct components programmatically

I'm new to unity and am having a bit of trouble getting my head around the architecture.
Lets say I have a C# script component called 'component A'.
I'd like component A to have an array of 100 other components of type 'component B'.
How do I construct the 'component B's programmatically with certain values?
Note that 'component B' is derived from 'MonoBehaviour' as it needs to be able to call 'StartCoroutine'
I'm aware that in unity you do not use constructors as you normally would in OO.
Note that 'component B' is derived from 'MonoBehaviour' as it needs to
be able to call 'StartCoroutine'
I'm aware that in unity you do not use constructors as you normally
would in OO.
That's true. A possibility is to istantiate components at runtime and provide a method to initialize them ( if initialization requires arguments, otherwise all initialization can be done inside Start or Awake methods ).
How do I construct the 'component B's programmatically with certain
values?
Here's a possible way:
public class BComponent : MonoBehavior
{
int id;
public void Init(int i)
{
id = i;
}
}
}
public class AComponent : MonoBehavior
{
private BComponent[] bs;
void Start()
{
bs = new BComponent[100];
for (int i=0; i < 100; ++i )
{
bs[i] = gameObject.AddComponent<BComponent>().Init(i);
}
}
}
Note that in the example above all components will be attached to the same GameObject, this might be not what you want. Eventually try to give more details.