- Home /
The question is answered, right answer was accepted
JS to C# Need some help.
if(ammo > 0)
{
ammo --;
var projectile = Instantiate(shot, transform.position, Quaternion.identity);
projectile.rigidbody.AddForce(transform.forward * 1500);
}
JS code
if(ammo > 0)
{
ammo --;
var projectile = Instantiate(shot, transform.position, Quaternion.identity);
projectile.rigidbody.AddForce(transform.forward * 1500);
}
C# code
why does it not work?
theres something wrong with the rigidbody in c#
Ins$$anonymous$$d of saying, "theres something wrong", can you show us or describe it in words? What you've glossed over be something crucial to our understanding of the problem.
Also, we may have to see more of your code to deter$$anonymous$$e what's wrong with it. With just a fragment, we can not test it ourselves if some of us want to. In fact, it may be that the code you've given isn't the cause at all, just the code that gets affected.
I think it's the part with the var. I normaly use JS but i think it should be:
GameObject projectile = Instantiate(shot, transform.position, Quaternion.identity);
Does that work?
Btw. I still agree with what jbarba_ballytech said. Next time please try to explain your problem in more detail then just saying "something is wrong".
tryed that and just got me this error
Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?)
Yes I actually did like i see now in fafase's answer. Like i said I don't do much in C#.
Fact is, UnityScript does the cast for you, that is why it does not show and work in Us codes but C# is way much more type safe and needs type to be explicitly defined to avoid surprise.
Answer by fafase · May 16, 2013 at 06:49 PM
The reason is that in C# Instantiate returns an object of type Object, the top class of all. It is required to cast the object to the appropriate type:
Type t = (Type) Instantiate();
In your case:
GameObject projectile = (GameObject)Instantiate(shot, transform.position, Quaternion.identity);
By the way, for some reason I cannot deter$$anonymous$$e, you are able to cast to GameObject or Transform. But trying to cast to Rigidbody for instance is not working. I reckon it could be due to some internal functioning based on the fact that all object have a GameObject and Transform but not necessarily a Rigidbody.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How do you climb a ladder 1 Answer
Object stops but then eventually breaks through 1 Answer
Tutorial level 2 Answers
this script in Javascript?? 0 Answers