#💻┃code-beginner
1 messages · Page 52 of 1
but that's very easy to google
That will go up to 4
Ints are max exclusive
Yes, but with integers, maximum is exclusive so if you want the number 5 to also show up you have to do a range from -5 to 6
because you're passing a vector3 as the Transform also written wrong (missing comma)
First off, the obvious thing, you have forgotten a coma between 'pipePrefab' and the vector
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Also, I'm not sure if that is even a valid way to instantiate an object, as I believe you need to pick one of these (picture) declarations
so get learning
start with a configured code Editor to actually show the correct parameters and underline errors
What exactly don't you understand? The declaration part?
Gotten this warning message on console,
Is this something I should be worried about?
I went through the forums, and it's looks like it's related to something called "unmanaged code" such as NativeArrays
not sure what are those but I did not touch any of those functions
if you are not using any of native or unsafe stuffs then not you problems
I just looked what native arrays are and It's something related to memory management unity's using?
what's "unsafe stuff" in this context?
similar to native
ah anything related to memory management?
but can crash the editor directly
When I get errors like these, I just restart editor to be safe. Started happening like once a day to me
and also why my character is not moving forward yet it seems to me to have done everything well
i would not get inputs inside FixedUpdate start with that
what game should i make
Hi Guys! I started my very first project in Unity and need little help (If I wroted on wrong channel then please let me know!). I have 3d model, animation and unity project. Any tips how to implement walk animation to game (any simple good tutorial but not 2hours long😅 ) ?
I just finished my cube runner game
not really a code question
Not a code question
Try #archived-game-design i guess
But also, go through the learn.unity.com pathways if you want guided stuff
what does "implement walk animation" mean in this context? also is this relavent to code , you're in a code channel
anything else like animations in #🏃┃animation
I mean by that when you press "w" then animation will start
not sure how this is relevant to this dc at all ?
make a bool parameter or use blend tree with floats
Input.GetKey or Input.GetAxis respectively
Saw someone create a polygon like this in a video. Is this not possible anymore?
do you have 2D package installed?
also not a code question
no? just pointing out the irrelevance of your post and its clutter
a mods gonna tell you the same thing lol
You've been warned so many times... why do you keep doing it?
This is a community and Nav is doing their part to keep it healthy and productive
Signal to Noise ratio bro
if its URP you should ask in #archived-urp or #archived-hdrp for hdrp
this is a code channel
Didn't say what "this" was referring to lol, but yup doesn't seem like a code problem
could be from postprocessing to lighting 🤷♂️
Ima guess they mean that big square of grass glowing lol
Apolgies Ill switch to a different channel
You can't use variables that don't exist in the current context
your first screenshot is clearly not the same context as the second
this is an algebra question not a C# question
x is 1000, always
not sure what that has to do with C#
what is the diffrent between
Public and Private int?
one is private and one is public
seems to be working now
If you just want it showing in the inspector, you can do
[SerializeField] private MaxHealth;
the SunData class does not have a sunset variable
the SunData.Results class does though
its already showing in the inspector irc
I know. I'm saying you can use what I wrote instead of making it public to do that
Having all your variables be public can be dangerous. Anything can modify it. You want to limit access
yeah, before i had like that... But i tried to remove that... but i don't know why i cant remove it... Do you know it? is there any way to remove it?
Not related, but you're really complicating yourself here with the hour string decoding. Look into DateTime.TryParse
You can do it in roughly one line
Remove what?
you just overcomplicated it
nono, the code like this works nice... but i don't know what those two lines do
Why you need another class is because of how your API returns data
those are field declarations, like most of the lines in this code
Yes. It sounds like it returns an object with two entires: a status string and a results object.
{
"status": "stuff here",
"results" : {
// the actual data
}
}
Something like that
hehe i always do that even if i don't want it
hmm good advice
rule of thumb: when you have an {object}, you need to create a class or struct type to deserialize it into
So there are two types here: the top-level object that holds status and results, and the type that will hold the contents of that results object
but here i'm not doing public GameData gameData;...
well, yes, it would make no sense for GameData to contain a GameData
Here:
DateTime d = DateTime.Parse(hereAMPM, System.Globalization.CultureInfo.InvariantCulture);
Then you can access everything you want on d. I pass the invariant culture in the second argument, so it does not fail if someone who uses a different system language plays your game
I don't understand what you are asking about.
I don't think they understand json objects and nesting
who?
You.
I think the most useful way to learn this would be to look at what happens when you serialize a simple class
Poor analogy. In the other instance you're doing public Results results; inside the SunData class, not inside the Results class.
Then look at how things work when you serialize a class that contains a reference to another class.
You will get nested objects.
{
"foo": {
"bar": 1
}
}
This is equivalent to
[System.Serializable]
public class ClassOne {
public ClassTwo foo;
}
[System.Serializable]
public class ClassTwo {
public float bar;
}
oh, i getted it... But it's true, i don't really know how JSON files works... I'm trying to learn it... i've watched a few tutorials of how to do it... But i think they are just showing me how to do what they want... And my head is being broken...
Thank you everyone for your help 🙂
Do this.
you're definitely overthinking it
Start from the top. Create a class that has a field for every entry in the JSON object.
Every time you encounter a new kind of object, create a new class that has fields for all of its entries.
If there is an array, create a list of whatever the array contains
Json is just a format, a way to represent data. Stuff like jsonutility or Newtonsoft already handle reading and writing it, so it's really just a matter of running a few tests to see what it does
Do you recommend me to test it on a new project?
Ok, easy, one sec
Okay, so, starting from the top
This is an object with two members.
The first member's name is "results". Its value is another object.
and status
The second member's name is "status". Its value is a string.
So, the class you deserialize this into must have two fields in it.
The "status" field will just be a string, so that's done.
The "results" field is another JSON object, so we need to make a second class
This object has a bunch of members that have strings for values, and one value that's a float
i tried to make a invetory system and ended up making a canculator
It contains no other objects, so we won't need to create any other classes.
Could you be able to dm me or to create here a post or something to talk with no more peple writing please?
Do you care?
public class Button_Controller : MonoBehaviour {
public List<GameObject> lights;
private List<Light_Controller> light_Controllers;
private void Start() {
foreach (GameObject light in lights) {
light_Controllers.Add(light.GetComponent<Light_Controller>());
}
}
private void OnMouseDown() {
foreach (Light_Controller light_Controller in light_Controllers) {
light_Controller.changeState();
}
}
}
am I using lists wrong here? the lights list has one light object in it, that object does indeed have a Light_Controller component on it but I am getting a null reference on the line in the first loop. The first inspector is the light object, the second inspector is the object with the script in question on it
huh, discord just said fudge those pics
FYI you don't need two lists here
just do public List<Light_Controller> light_Controllers; and abandon the GameObject one
how do i grab the components?
whattt
you can then delete your Start() function too
i always thought comonents were only accessible through the GetComponent method
you thought wrong
yeah you almost never need to reference the GameObject directly
2 years unity experience btw lmfao
that would have been very useful to know in the development of my last game at college haha, so many lines wasted on grabbing components
wait until you learn you can pass a component reference to Instantiate and it will return the instance of that component that was created on the gameobject you spawn
you typically only need to type GameObject if you are specifically using the reference to call SetActive or manipulate the object's layer
i really wish i could see how many lines in my old projects reference GameObject when it wasnt necessary
I blame all the tutorials
tbh i dont really get this lol
public MyScript prefab;
void Spawn() {
MyScript instance = Instantiate(prefab);
}```
tutorials suck just cuz it's hard to teach someone everything and not just the specific pieces
where MyScript is a script on the root object of the prefab
so it's fetching the component of a new gameobject created?
the parameters for Instantiate say it needs to be an object passed to it, how does it work with a component reference
this is using the generic version of Instantiate which is lower on the docs page. it returns the same type you pass to it
obviously it would still need to be a UnityEngine.Object though
ohhh, i see now
so this is a method of creating duplicate objects and grabing the same component again in one line?
yep
public class Bullet_Controller : MonoBehaviour {
private int speed = 10;
}
public class Gun_Controller : MonoBehaviour {
public Bullet_Controller bullet;
private void Start() {
Bullet_Controller bulletCopy = Instantiate<Bullet_Controller>(bullet);
}
}
really simple example but is this like the proper use of it?
basically just ripped their example on the docs but with a component instead
unless their example of "Missle" is just a poorly named controller lol
you don't need the generic type parameter on the Instantiate call, it's implied from the parameter you pass to it, but yeah that's how you would do it
that's sick
noted for future use, thank you
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
how can I make this camera following code smoother? It technically works, but it's really jerky
use cinemachine instead
you are also moving in a frame dependent way. your code will move the object faster at higher framerates
The object is the camera, so it doesn't matter at faster framerates
lol yes it does
imagine you're playing your game and suddenly it starts running very well at a few hundred frames per second instead of like 30 or 60. suddenly your camera is moving much faster. then later on it drops back down to like 30 frames per second. now your camera is moving much slower than it was
I moved the function to FixedUpdate, I need help with smoothing now
what's cinemachine?
for that stuff would FixedUpdate be the way to go or something else
Okay this is a basic 2D follow cam cinemachine seems like massive overkill
just throwing it in FixedUpdate isn't a great idea either. they should be scaling the movement by deltaTime to make sure it moves consistently no matter the framerate since they are just incrementing the position
seriously, just use cinemachine. it's excellent and will be far better than any camera code you could try writing
Create camera -> Set follow target is not overkill
You don't have to even use all of the wonderful features
I third using cinemachine. It almost should just be the default camera in unity
But I guess there are some uses for the normal camera still
cinemachine is 🐐
that was surprisingly easy, the way the first five results were done up like "Cinemachine won five cinematography engneering awards" made it seem like a whole process to learn
so, problem
I need the camera to be able to pixel perfect teleport 10.24 units when the space texture edge is reached
can cinemachine still do that with the tracking?
I also need to reimplement a barrier the camera cannot track past
yo how to make this code work
if (collision.collider.CompareTag("Blue") || collision.collider.CompareTag("Blue"))
{
Destroy(collision.gameObject);
Debug.Log("Worked");
}
#🎥┃cinemachine
also for that specifically you can use a cinemachine confiner
i'm gonna bet the issue is not with this code specifically and is probably related to your setup for receiving a collision message
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nope because it used to work
what about that is not working then
checking the object that has the script own script
Quick question. I am facing an issue where If I create a new quad, It's having this blue tinted color. It has default material only. how do i fix it?
...what? You mind rephrasing that in a way that makes sense?
well you're not checking this object's tag
and you should know that just from reading your code and from our previous conversation #archived-code-general message
Your light probably has a slight tint to it. I think in URP there's a color to the light by default
this color was by default
ok so there a hammer and this hammer has this script then it checks for collision then it check for the tag of object collided with and the its own tag but checking its own tag doesnt work
Try making a new material and making sure it's set to pure white if you want pure white
there could also be color in the default material
well iam using its own game object
- What is checking this object's own tag
- Why is checking this object's own tag, you already know what object you put it on
I created and attached a new material which has color fff, but still the quads are blue shade
Can you show the inspector of the quad
becuas eof this this one script controls two part of a hammer red and blue each part can hbreak spicfic object so i need to check tag of which on hit it and which one it collided with
So, it seems like what you'd rather do is check if the tag of the object collided with matches the tag of this object
this worldBox material is pure white
So you should probably do that instead of checking the collided object twice
ok but idk how i dont remmber how to
Do you know how to check the tag of an object
ye using compare tag
do you know how to get the tag on an object?
i'll give you a hint: #archived-code-general message
So, use comparetag to see if this object's tag is the same as the other object's tag
how? because compare tag compare the tag you right the name of to the actualtag thats on the object how do i change it to compare the object you collided to with the object that has the code
CompareTag checks if the object you call it on has the tag you pass as a parameter
Get the tag of the other object, pass it to compare tag
what i said
yo i actually can figure it out
if (collision.collider.CompareTag(gameObject.CompareTag("Red")))
blanking so hard so tired
you need to get the tag from the gameobject
Finnaly i stopped blanking and remmebered
if (collision.collider.CompareTag(gameObject.tag))
bro so tired that i blanked so hard that i forgotcoding
thank you @slender nymph and @polar acorn
can someone pls help me out here
I would check to see if it's a lighting thing by creating a directional light and playing around with it or any existing ones
I don't understand
this is a code channel
check to see if shining a light on it makes the colors what you expect, and if that doesn't work, ask in the channel for lighting or other graphical stuff
if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
if(Vector3.Distance(currentPlacement, hit.point) > stepDistance && !isMovement)
{
lerp = 0f;
newPos = hit.point;
}
}
if(lerp < 1)
{
Vector3 pos = Vector3.Lerp(currentPlacement, newPos, lerp);
pos.y += Mathf.Sin(lerp * Mathf.PI) * stepHeigh;
lerp += Time.deltaTime * stepSpeed;
currentPlacement = pos;
}
else
{
currentPlacement = newPos;
}``` the object is not lerping, why ?
where are you using the currentPlacement variable
Add this before your lerp:
Debug.Log($"Lerping between {currentPlacement} and {newPos} at {lerp}");
it's only zero
So it seems that you're never changing lerp anywhere
What is stepSpeed, add that to the log
or maybe i'm setting lerp to 0 constantly
Probably
What's the best way to tell the main game manager script when to increment the score from an instanced laser destroying an instanced asteroid?
I tried adding public mainGameManager and attaching the root, but it claimed Type Mismatch
sounds like you've tried dragging a scene object into a prefab which you cannot do
Whatever spawning the projectile could pass in a game manager reference
i'd personally look into events for that. but you can also check out this resource for referencing scene objects when you instantiate a prefab https://unity.huh.how/references/prefabs-referencing-components
Probably an event. But that isn't your issue
can anyone help me get breakpoints working with vs code/ unity?
installed the unity extension
!vscode
bro i still need help ice had a look at it
Did you install everything required, and did you modify Unity's configuration so it uses what was just installed?
why not? didn't you say you had a look at the guide the bot linked?
Everything mentioned in that link should be enough to make it work
If it's not the case, then start checking that you did the steps correctly, then double-check
Then explore what could be wrong, looking at the VSC console should be a good start to see if the project is detected, compatible, and loaded
I need help with a grounded function for jumping using rays. I'm casting a ray downwards on a composite tilemap collider but it seems to not detect it at all. Works fine on other objects.
Here's the code for the jump function:
public float minFloorDistance;
public Vector3 raycastOriginOffset;
if (Input.GetButtonDown("Jump")
&& Physics2D.Raycast(this.transform.position + raycastOriginOffset, -Vector2.up, minFloorDistance))
{
body.AddForce(Vector2.up * jumpForce * 10);
}```
are you sure you aren't perhaps starting the raycast too low?
if you start the cast inside the tilemap's collider it likely won't detect it
oh
i got it working in ther end
idk how i did
but i did it in the end
hol on
it worked
then it stopped
what is suppost to be in my launch.json file
i tihnk i done something to it
i was wondering if theres a way to put the money variable into the text so it says how much i have in the text instead of 0 yknow idk why i cant find stuff online
nvm im dumb i got it
good
I had the ray as low as I could get it before it hit the player's box collider. Tried using layermask to ignore it but it just disabled jumping on everything.
sounds like you did it wrong
yo it still aint working
this is the error im getting
Unable to determine debug settings for project 'C:\Users\Vas\treasure game v1.0\Assembly-CSharp.csproj'
First off, remove dots and spaces from your project path or you will run into problems along the way
VSCode has some problems with it if I remember correctly
ok
Can anyone help?
I am trying to make crazy zombie boss do a head spin dancing animation.
It is in 3 parts from Mixamo, the 3 animations make one complete dancing animation.
It was working before but I went to settings and I increase exit time to a larger number and Crazy zombie boss stopped doing the headspin dance animation.
I sent the script and what is going on in the inspector
using UnityEngine;
using UnityEngine.AI;
public class CrazyZombieBossAnimationControl : MonoBehaviour
{
private NavMeshAgent navMeshAgent;
private Animator animator;
private bool isAnimationPlaying = false;
// Define normalized time thresholds for animations that should stop movement
private float animationStartThreshold = 0.0f;
private float animationEndThreshold = 1f; // Adjust this value based on your animation's length
private void Start()
{
// Get references to the NavMeshAgent and Animator components
navMeshAgent = GetComponentInParent<NavMeshAgent>();
animator = GetComponent<Animator>();
}
private void Update()
{
// Check if any of the specific animations are currently playing
if (animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie hip hop dancing") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie taunt") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie hip hop robot dance") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie fall flat") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie dancing running man") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie arm wave") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie cross punch") || // Added
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspin start") || // Added
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspinning") || // Added
animator.GetCurrentAnimatorStateInfo(0).IsName("Crazy zombie headspin end")) // Added
{
// Pause the NavMeshAgent's movement
navMeshAgent.isStopped = true;
isAnimationPlaying = true;
}```
2
else if (isAnimationPlaying && animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= animationEndThreshold)
{
// Resume the NavMeshAgent's movement if the animation has reached the end threshold
navMeshAgent.isStopped = false;
isAnimationPlaying = false;
}
}
}```
Anyways, it sound like the problem is with the animator setup, not the code..?
can you walk me through this
First of all, your going to have a far better time having condensed and simplier names for those animation paramaters
Are you sure you need the exit time there at all?
Also #🏃┃animation
someone said have exit time from walk to headspin start
not sure I just tried it withoyt has exit time the animation did not do start
im lost
any help i appreciate
my brain hurts
Why are you accepting suggestions from strangers without understanding them?😅
Just return it to how it was before..?
I did and its still not working
can i call you and you walk me through it with discord screenshare
im lost
been on this for like 3 days
I'm at work. I can only help via messages when I have some free time. This is true for most people here, so don't expect someone to hop in a call.
That being said, your issue is complex and really hard to debug for anyone that doesn't have access to your project.
To solve it you'll need to learn to debug such issues. Start from figuring out what's going on first. Watch the animator live, while the issue happens. Does it enter the state at all? Does it enter and then exits it? Why? Are the parameters changing? Where are the parameters set? Etc...
You need to learn to ask these questions and explore them on your own.
ok ill try to do it myself but if i fail can you help me?
in return ill help you with anything in your game
We can only help you with specific questions. If there's something specific during your debugging, that you don't understand, feel free to ask. It might not be me, but someone would definitely help. Just don't let the other person do all the work for you without even having access to your project.
how do we disable shadows on a gameObject via code?
ill show you my project in sceenshare
No, ask the question here and provide the necessary info
As I said, I don't have time nor desire to get into a call or screen share. You can share the details via a screenshot of video here. This way more people would be able to help you too
ok but I feel with screen share we could get to the bottom of it quick, and ill learn what to do next time
As I understand it some of the people in here are industry leading experts that people would probably pay a lot of money to have hop in a call with them
No, I'm just watching a four hour documentary on the Unabomber and I don't wanna pause it to diagnose a null reference exception
The general vibe of a server like this, respectfully, is beggers can't be choosers.
The best way to get help here is to make it as easy as possible for people to understand your problem and what you need as a solution
Digital footprint 😂
If you need active screenshare/call time then your not going to have many people available to assist you
i fixed it
using UnityEngine;
public class CrazyZombiesDanceAnimationActivator : MonoBehaviour
{
private Animator animator;
private float danceTimer = 5f; // Time interval for dancing
public string[] danceAnimations = {
"Crazy zombie hip hop dancing", "Crazy zombie taunt", "Crazy zombie hip hop robot dance", "Crazy zombie fall flat", "Crazy zombie dancing running man", "Crazy zombie arm wave", "Crazy zombie headspin start", "Crazy zombie head spinning", "Crazy zombie headspin end" // Add the names of your dance animations here
};
private void Start()
{
animator = GetComponent<Animator>(); // Get the Animator component attached to this GameObject
}
private void Update()
{
danceTimer -= Time.deltaTime;
if (danceTimer <= 0)
{
PlayRandomDanceAnimation();
danceTimer = 8f; // Reset the timer for the next dance
}
}
private void PlayRandomDanceAnimation()
{
if (danceAnimations.Length > 0)
{
int randomDance = Random.Range(0, danceAnimations.Length); // Select a random dance animation name
Debug.Log("Triggering " + danceAnimations[randomDance] + " animation");
animator.SetTrigger(danceAnimations[randomDance]); // Set a trigger with the animation name
}
}
}```
had to add the names of the animations in the inspector and in the script
In the future, if you plan on chaining animations, you may want to use a timeline.
Congratulations! No documentaries were interrupted in the process
That's great and I hope you learned something in the process. Regarding a call/screen share, if you were fine with waiting untill my weekend and when I feel like making a call(which I usually don't, at least not with random people on discord), then sure.
Besides, there's nothing you can't share in a video or screenshot. I feel like this is just a lazy way to get your issue solved for you without putting any effort. If you have went through learning the basics, you wouldn't have a problem with sharing the relevant pieces of information for people to help you.
I was on this for 3 days
i was out of luck
I tried joining a C# club to learn near me but no reply yet
my demo is almost compete its just im stuck on ammo pick up
I am available any day for screenshare if you can help me with this
There are plenty of learning materials online.
If you haven't gone through any basics yet, you should really do it.
And if it wasn't clear enough, I(and most people here would say the same) really don't feel like joining a call regardless of the time.
Hi all, I was trying to add a method for downloading a set of 3 png's (or just a zip file of them) to the users computer. I don't need to generate these images at runtime or anything, it's just a set of icons that I've made for a user to upload into their twitch dashboard. I want to include them in the build, rather than having to host them online somewhere. I guess ideally I would use a native explorer/finder dialogue to choose a location to save them. Its a bit hard to google this one, if anyone could point me in the right direction that would be much appreciated 😊
I guess I could just include them in the download and point users there, maybe i'm overcomplicating it...
Google "unity file explorer" there are plenty of assets that implement it.
Thanks this was it, I just needed the right keywords! ❤️
how do you get the rotation angles for an object
not local but global angles
my inspector says z is -84
but my console is printing out 0
Debug.Log(transform.localRotation.eulerAngles.z);
wait
i am so confused
i am using
Debug.Log(transform.localRotation.eulerAngles);
to print this out to the console
why are the values flipped for the x and z
Are you sure you're looking at the correct object?
these may be the same rotation. rotations are stored in quaternions so when you want it as euler, they have to convert it. there are many euler angles that can represent a single rotation
what are you trying to do with the rotation?
i am using the rotation to determine what side is up for a dice
i am only using the x and z rotation
also you can see examples of this by simply setting the rotation in inspector, then it suddenly changes to become something else. I think if you set Y to 180, itll change X and Z to 180 instead
why does this happen?
hm maybe u could have a child transform object as each face of the dice, then check through every transform to see which transform.up is closest to vector3.up
definitely not the most efficient but just a thought
Because its stored as a quaternion, then converted back to euler angles for you to read in inspector.
https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
When using the .eulerAngles property to set a rotation, it is important to understand that although you are providing X, Y, and Z rotation values to describe your rotation, those values are not stored in the rotation. Instead, the X, Y & Z values are converted to the Quaternion's internal format.
Also the inspector shows localEulerAngles not eulerAngles
i am just going to search up a youtube tutorial on rotation and euler angles and hope for the best
Ok, thank you for the advice, i will look into it
honestly i would just move onto a better solution. You will not get the results you want from this easily
why not?
you would have to hardcode sooo much to get this working
really?
i only have like 6 if statements for each of the sides
ofc it doesn't work but i am working on getting the right values
getting the right values is the hardcode in this case
I would get the three dot products, one for each side (XYZ) vs. Vector3.up
What would you do if a dice was also not fully flat on the ground? you now cant compare directly to euler angles like 0, 90, 180. You would have to check if its closer to 180 than 90, but also in which direction? What if the angle is something silly like (45, 0, 180), what did you roll?
It may not be the best solution but even just comparing the transform.up of an object on each face to vector3.up is already way more reliable
Yeah if the ground can be tilted, you would have to use the ground normal instead of world up
it will always be flat but that will be useful to consider if it wasn't
i have no idea what the three dot products is but i will look into everything you talked about
Thank you for your time to answer my question
if you are rolling the dice via physics, then theres already a chance it wont be fully flat on the ground. Assuming there is more in your world than just a single dice
Even if the ground was completely flat?
Do you have multiple dice?
no
Nothing it can collide with?
except the ground
if its literally just the ground and dice, then yea should be flat. If your solution relies on it being flat though.. thats really not a proper solution
Semi-pseudo code of how I would go about it```cs
Vector3 dotY = Vector3.Dot(transform.up, Vector3.up);
Vector3 dotX = Vector3.Dot(transform.right, Vector3.up);
Vector3 dotZ = ...
if abs of dotY is the largest of the dot products
if(dotY > 0)
// Facing up = 6
else
// Facing down = 1
// Etc
Might be a little janky but honestly could just have 6 transform points on each side of the dice and see which one has the highest world position, no?
it should collide with only one thing (enemy, or enemy's head) at a time and perform different actions according to that (gameover or destroy enemy object), but it keeps colliding with both of the things at once for some reason :(
I have a simple targeting system for my Ai in my 2d game it works fine for the first couple of targets but then its start rotate on both x and y axis.
Cant figure out what im doing wrong, feels like ive done the exact same thing before without problems.
private void HandleTurning()
{
if (target != null)
{
Vector3 targetPosition = target.position;
Vector3 playerPosition = playerGameObject.transform.position;
playerDirection = (playerPosition - targetPosition).normalized;
playerGameObject.eulerAngles = Vector3.RotateTowards(playerGameObject.eulerAngles,new Vector3(0f, 0f, WorldSpaceUtils.GetAngleFromVector(playerDirection)),50f *Time.deltaTime,50f*Time.deltaTime);
WorldSpaceUtils.GetAngleFromVector(playerDirection)),1f*Time.deltaTime);
}
}
The the get angle function looks like this
public static float GetAngleFromVector(Vector3 vector)
{
float radians = Mathf.Atan2(vector.y, vector.x);
float degrees = radians * Mathf.Rad2Deg;
return degrees;
}
wrong channel
@chilly moss if you export fbx you can set units in some dccs
at least in Houdini, think the option should be there in Blender as well
hey guys, is there no .data like this? yesterday someone here told me to do like that but it says data doesnt exist as a method.. what I am trying to do here is basically instantiate an enemy using only 1 prefab and assigning data from a scriptable object to this enemy so I can spawn dif enemies using the same prefab
how can I have only 1 prefab and instantiate it on the scene dif enemies, using only 1 prefab and assigning the SO to this enemy that will contain dif values and so on so I can manage a good way to have multiple dif enemies using only 1 prefab so I dont need to have 100 prefabs if I have 100 dif enemies
Because you either have not defined a variable named data or you have not made it public
This is basic c#
i thougt that data was already something unity has .. anyways anyone know a way that I can instantiate enemies using 1 prefab with dif things? or there is a better way? i am 3 days struggling with that and I am not progressing
As far as I am aware Unity does not have a data variable available, and even if it does it would exist for a reason. If you want a place to store your data in the class, you should make an actual variable to store it.
ok, but what about my other question? 😛
The answer to the other question is the same as to the first question. Make a field in Enemy1 that stores a reference to the SO and then assign the SO to that field
and don't use the ScriptableObject type, use the actual type of the SO
hm ok, well I think i will still be stuck for a while with that. Or i will just go the hard way that is creating a dif prefab for all the dif enemies I have as ScriptableObject or any other sort of ways i am trying to optimize and not having 1000 prefabs I am not managing to do it..SO what ever for now I will create 1 prefab for each dif enemy . it is what it is.
What do you mean "stuck"? What's the issue with that?
well I am beginner, 2 weeks into unity.. progressed a lot with my mini game so far, but now I am stuck. I am trying to do something and I am not being able to do it. Tried this discord many times during the days, google, chatgpt, but surely I am the prob. my game for now will not have more than5 enemies or so, but who knows in the future, so I wanted to already implement a way that I can have a lot of dif enemies with low memory use or in an effective way. Not sure which one it is, but so far as I checked people say SO is the way to go with 1 prefab. But I am not being able to do it. As when I use the instantiate and the prefab, I am not sure how to attribute to that prefab dif SO, So I have dif enemies being spawned using the sabe prefab but dif values from the SO. Also not sure if that is the best way. So maybe I will just forget about it to be able to progress and learn more stuff and use just 1 prefab for each enemy eve tho this is not the best way to do it.
I described how to do it here
well yeah, for you might be simple to read and understand what you wrote, but for me its not so clear as I am still a nb and i ned time to process and understand things if not more detailed explained or shown in code. But I apreaciate your answer I will try to understand it better.
What's the type of the SO?
that you mean?
In the Enemy1 class add
public EnemySO data;
in the class that instantiates the enemy change the SO list type to
[SerializeField]
private EnemySO[] listOS;
Then your enemyOne.data = ... code works and you can access the SO through the data field in the Enemy1 class
Hi all, I have a screenpointtoray firing and colliding with a 'ground' object (3d) with a custom crosshair attached to the mouse pointer. Is it possible to 'lock' the mousepointer inside the area of the ground object? (ie, if the ray is hitting the ground act as normal, but if the ray isn't hitting the ground, as in hitting empty space, the mouse cursor can't move past the edge of the ground?)......not sure if that's explained very well. lol.
And please stop sharing !code through screenshots 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh ok, worked, HA genius, thank you.
Oh, sorry done it like for a week now no one said anything I didnt know it was a prob. Next time will do as you said. Thank you!
It's ok, it's just easier to help when you can copy-paste the code instead of having to rewrite it
true
Another question, here in this SO code ```cs using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "EnemySO", menuName = "enemies/enemy1")]
public class EnemySO : ScriptableObject
{
public string type;
public int health;
public int exp;
public int attackDamage;
public float speed;
public float detectionRadius;
public float avoidanceDistance;
public float repulsionForce;
public GameObject player;
public void Print(){
}
}
Can i put a variable here to change the color of it controlling in the inspector? like acs GetComponent<SpriteRenderer>();
becuase for now I dont have a sprite to add to it, so i just want to change the color of the enemies to keep it simple for now
I think Color type is serializable? So you could do public Color color; and then use that to change the sprite renderer color
oh ok, will try thank you!!
worked.. thank you again !
Any ideas why I would get an error on that line? I mean I can read the error, but not sure how to fix it. ```cs
[SerializeField]
private GameObject _enemySO;
void Start()
{
_player = FindObjectOfType<Player>();
InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
}
void Update()
{
if (testing == true)
{
Enemy1 enemyOne = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
Enemy1 enemyTwo = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
enemyOne.data = listOS[0];
enemyTwo.data = listOS[1];
testing = false;
}
}
The field must be of type Enemy1
but it is no?
Enemy1 enemyOne = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
yeah but that way it doesnt instantiate in the scene
says object you want to instantiate is null
Then _enemySO is null 🤷
and if I use _enemySO = FindObjectOfType<Enemy1>(); on start
it is not null anymore
but also doesnt instantiate
Then either something destroys it immediately or it is instantiated but you just don't notice it
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok, so i create a new project to test it. And that is the setup I have, and with this simple setup you might be able to spot it and help me out maybe. I have just 2 scripts, EnemyControoller and SpawnManager and 1 prefab. The code from the EnemyController now is empty as this is a test. And in the SpawnManager I have: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
private EnemyController enemyController;
private bool test = true;
// Start is called before the first frame update
void Start()
{
enemyController = FindObjectOfType<EnemyController>();
}
// Update is called once per frame
void Update()
{
if (test == true)
{
Instantiate(enemyController, new Vector3(3, 3, 0), Quaternion.identity);
test = false;
}
}
}```
and gives me the same thing
what am I missing here?
obviously
enemyController = FindObjectOfType<EnemyController>();
is not finding anything
yeah as it is a script and not a game object, but If I try to do something like that ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
private EnemyController enemyController;
private bool test = true;
// Start is called before the first frame update
void Start()
{
enemyController = FindObjectOfType<EnemyController>();
}
// Update is called once per frame
void Update()
{
if (test == true)
{
EnemyController enemy1 = Instantiate(enemyController, new Vector3(3, 3, 0), Quaternion.identity);
test = false;
}
}
}```
and instead of using the EnemyController type use Gameobject
it will give me an error
What I need is to assign to a variable the instantiate method
Did you read the FindObjectOfType documentation to see how it works?
oh, yeah, but wait I might not being able to say what i want. give me a second will do a test sorry, sometimes I confuse stuff when I ask as I am still a nb
on my actuall game code I have this code here in my SpawnManager, BUT I get an error in the enemyOne.data and enemyTwo.data saying that Gameobject does not contain a definition for data. So how can I access that variable that is inside my enemy1 script if i need to use a gameobject type to instantiate it? ```cs
private GameObject _enemySO;
void Start()
{
_player = FindObjectOfType<Player>();
InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
}
void Update()
{
if (testing == true)
{
GameObject enemyOne = Instantiate(_enemySO, new Vector3(3, 3, 0), Quaternion.identity);
GameObject enemyTwo = Instantiate(_enemySO, new Vector3(-3, -3, 0), Quaternion.identity);
enemyOne.data = listOS[0];
enemyTwo.data = listOS[1];
Instantiate(enemyOne);
Instantiate(enemyTwo);
testing = false;
}
}```
whats wrong with the code
that is so complicated, i might just create 1 prefab for each enemy, 3 days and no progress
I give up
hahaha
using UnityEngine;
public class YourScriptName : MonoBehaviour
{
public GameObject enemyPrefab; // Assign your enemy prefab in the Unity Inspector
public List<YourDataType> listOS; // Make sure you have a list of your custom data type
private Player _player;
private bool testing = true;
void Start()
{
_player = FindObjectOfType<Player>();
InvokeRepeating("SpawnEnemy", _spawnCount, _spawnDelay);
}
void Update()
{
if (testing)
{
// Instantiate two enemies
GameObject enemyOne = Instantiate(enemyPrefab, new Vector3(3, 3, 0), Quaternion.identity);
GameObject enemyTwo = Instantiate(enemyPrefab, new Vector3(-3, -3, 0), Quaternion.identity);
// Assuming YourDataType is a custom script or component you want to attach to the enemies
enemyOne.AddComponent<YourDataType>().data = listOS[0];
enemyTwo.AddComponent<YourDataType>().data = listOS[1];
testing = false;
}
}
}
use this you have tho change some things cuz i dont know what project ur doing
so where is the .data varaible
on my enemy script that I assigned to the prefab I have. So the goal is to have 1 prefab with 1 script to control its basic things and I have a ScriptableObject script to control life, damage, etc... So what I wanted is that my SpawnManager would manage to Spawn dif enemies using 1 prefab only and control their dif stats etc with a SO
ye
exactly .data is on a script of type Enemy1. Not on GameObject which is what you are trying to access. So get a reference to the Enemy1 script from the GameObject
what game are you making?
its a game like vampire survivors or halls of torment
ok sounds fun
I already managed to progress in a lot of things.. but now I want to be able to control that part of the enemies to continue
ok
here is what I have so far
but now I want not only 1 enemy to spawn
i need more with dif size, color, etc for now as sprites and stuff I will add later in the game when the logic is finished
hmm not on gameobject? not sure if I understand. so which script i need to put the data variable?
okay looks nice
you already have a .data variable on your Enemy1 script do you not?
yes
and the Enemy1 script is attached to the prefab is it not?
yes
so it is also attached to the Instantiated GameObject. So you can get a reference to it
Anyone? 😦
do you not see that you are trying to access .data on a GameObject not on a Enemy1 object?
oh
do you mean like a decal be applied on the ground when it collides?
No, I'll see if I can explain it better. Gimme a minute.
you want to lock the mosue cursor inside the area of ground projected to scene?
As I said, you need to get a reference to the Enemy1 script from the GameObject and, tbh, if you do not know what a reference is you should be following some basic c# tutorials not trying to make a game
i think this is impossible, but you the position of crosshair can be unchanged if the ray is not hitting the ground
Okay, very simple visual aid.
Crosshair is moved around by the mouseposition, I'd like the mouseposition to be 'clamped' inside the groundplane
so that you can assign to it's .data variable
@vast yoke
yes impossible, mouse position is data that the OS given to unityengine, so you can just clamp the position of crosshair
Ah okay. Think I thought of a way around it though.
im having trouble!
my character third person isn't activating
those are the error problems
can someone help please?
no.
Imagine a GameObject is like a book and you want to write on page 10 of that book
At the moment you are trying to write on page 10 without having opened the book.
If you want to write to page 10 you need to open the book to page 10, then you can write
yeah the mouse pointer cant be clamped but you could have a custom mouse pointer that is clamped.
Double click the error message and it should show you where the error is and then show that.
Yeah, I have an empty gameobject following the end of the raycast (sticks to the floor), so I'm just going to use that as the target and turn off the cursor when it goes outside the bounds of the ground object.
Sorry, I cannot help you further. You need to learn a lot more about C# and Unity because you just do not have enough understanding about what you are doing. Please go and follow some basic tutorials
its my first time getting a character module to work in my own level, aside from a capsule, it would be tough
the code looks like its running fine
Yeah the error basically means that the script can't find something it needs. Can you show the inspector for that script please?
ok
It is only hard to understand for you because you have no knowledge of the basic fundamentals, these things you need to learn first
Okay, you haven't assigned your Input Module or Camera in the inspector.
sounds like a plan :)
which one?
I don't know anything about the new input system I'm sorry so I don't know. 😕
But that would make sense.
im not sure where the input is located at
Based on the name that's for UI stuff. But honestly I don't know. 😕
try it, see what happens. lol.
does anyone know what to do?
Drag it in, and ddrag in your camera and see what happens.
Hey guys.
I made a plane water in Blender 3d, I want the water to be endless in Unity. How do I achieve this? The water is also meant to be animated, which is done through the animations in Blender. Is this possible?
Do i animate the block in blender or in unity?
Unity now has a native Water system. Probably best to use that tbh
run it
the character did not progress to moving around
Does it work for low poly water?
I think that might be related to your input system, but tbh like I said I know nothing about it so can't help 😦
You don't need an object beyond an empty gameobject. Google it, fair few decent tutorials on how to set it up.
does anyone know how to do it?
Do what exactly?
If this, then you need to be more specific about the problem
First thing I turned up on google.
https://blog.logrocket.com/building-third-person-controller-unity-new-input-system/
ok ty ill be doing that as soon as possible
if anything comes problematic i will report here
Hey guys, If I have an Enemy Prefab using a EnemyAI script. I also have a ScriptableObject Script with some variables, like life, damage, etc.. If I want each enemy to have a dif speed and movement variations, should I implement the move() method in the EnemyAI or in the ScritableObject?
Definitely EnemyAI.
ScriptableObjects are mostly for immutable data.
Ok, I already have it there. and that is the code ```cs
private void Move(){
Vector3 MoveDirection = _player.transform.position - transform.position;
MoveDirection.Normalize();
_rb.velocity = MoveDirection * _enemySO.speed;
}``` the problem is each enemy have a dif speed, so when I instantiate 2 dif enemies, how do I do in the _enemySO.speed to get the speed of the dif enemies? as you see here for instance, anemy1 has 2 speed but enemy2 has 4... and if the method is in the EnemyAI I am sayingjust to get the speed, and how does he know if its speed from enemy 1 or 2 ?
When you spawn an enemy assign a corresponding data SO to it.
how do you assign _enemySO? It should already work the way you want it to
I also have some doubts regarding that player prefab reference in the SO😅
uhmm hello guys uhh if i had a problem which channel do i chat?
like... unity got error
the only way I found to make it work for what I want.. hahaha.
Well you're halfway through. You just need to use the other SO in the array as well.
which one?
Ah, wait. Didn't notice that error.
You need to get the enemy component from the newly instantiated enemy object and assign the SO to it.
Whichever you want to use 🤔
Something like that?
You need to use GetComponent on the enemy object. I feel like there are some C#/unity basics missing...
yes exactly, that is why I am in the Code-Beginner channel 😄
Yeah, I have a really strong urge to just send you to learn
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
No. You get it wrong. You're supposed to learn these things by following a course. Not asking random people on discord.
Oh, ok
firstly, I would change
private GameObject _enemySO;
to:
private Enemy1 enemyPrefab;
Then you need to reassign it in the inspector, drag your Enemy prefab (not the SO) into this field. Now when you spawn them;
Enemy1 enemyClone = Instantiate(enemyPrefab);
enemyClone.data = listOS[0];
I thought here was a place to help people that are beginner and starter in coding with unity, Sorry, will try 750h of course to get my answer. and in some weeks I am back here again to ask you. Thank you for your time.
Thank you, that is what I am asking 3 days in this discord
Have all a great day and lovely weekend
This is a place to help people after they made some effort. These are all very basic things that you waste everyone's time by not knowing.
Really, just go through the beginner pathways(it's gonna take a week at longest), and you'll see how much more you understand and can solve on your own.
And if you still don't understand something after that, come back and ask proper questions.
Hello, I am stuck in a coding part from the section of the link
it has 3 errors, that the code it provided had errors in it
3 days trying non stop, if that is not effort, waking up 7am and going up to 16h with unity open and trying to solve my issue, while I search google, discord and other sources, You think I opened unity and asked questions here? I am days trying something, that is why I asked here. I just come here after trying for a long time, also because its nice to try hard . that makes u learn better.. but you are not here to see how much effort I did before making those questions, you are just assuming i didnt do any effort. I already programmed games in java and other ways but Unity is Unity with its own ways to do stuff, and I am not yet used to it.
those 3 days could have been spent learning the basics so that you don't have to spend 3 days trying to troubleshoot an issue that would be solved by just . . . learning the basics
what are the errors?
okay and do you have a type or namespace called Controls somewhere?
yes
where
line 5 / 12 and 19
no, those are attempting to use that type. where have you defined it?
Spoiler: they haven't
after monobehaviour, private, and controls
Or not ticked the "Generate C# class" checkbox
These are points where you try to use the Controls type. Where have you defined it? As in you need to have some public class Controls { } somewhere, whether you created it yourself, or not
This seems like it's a class generated from an Input Actions Asset (from the new input system package)
its a file known as controls.inputactions
Make sure you named it Controls, otherwise it won't find it in your code
With an uppercase "C"?
Okay did you check this? ^
And did you save the asset?
Okay ticking the check box will generate the class Controls for you, so you will be able to use it now. Go back to your code
they may need to eliminate any compile errors before it will actually generate the code
All good my friend, some are willing to help more than others. And its all good with that.
some may be more willing to help more than others, but you seem to not be willing to put the effort in to actually learn. so don't bother pinging me again as i will not be offering you any help until you've demonstrated at least a basic understanding of what you are doing
Sure, no problem, I dont know why you think I am not willing to put the effort in to actually learn. Not sure if you are here next to me all morning watching what I am doing. But I dont think so. I might also not have a good english or understanding of the term beginner as it says here in code-beginner:
outright refusing to actually do some learning and just throwing your face at a problem for 3 days as a result of not learning and still refusing to learn is not effort. it is laziness. if you do not even put in the effort to learn what the fuck you are actually doing, does it really count as being a beginner? because you haven't even begun yet
it's okay though, you don't need to bother replying. i have already blocked you and do not intend to offer you help
No problem my friend, 17k people on discord to help with future problems. You are just 1 angry guy, I will not miss it.
I haven't been in this discussion but from what I can see...
750h is everything they have to offer. If you were willing to tackle this problem for 3 days straight then you'd be more than capable of completing a beginner course in half a day and learn all the basics which you are struggling with right now
is there a simple way to connect an empty to an already animated object? so that it would move with it?
make it a child of that object. or use a ParentContstraint or PositionConstraint component
Can I be honest? I completed a 3 months Java Bootcamp, and worked in the area for 1 year. But unity has its own terms and ways to do stuff I am just not yet used. I created very complex games only with Java. I also just completed a 200h course in unity from Udemy and created 3 games with it.. even tho what I am trying to do now I didnt learn yet and all the material I got I still cant understand.. that is why I came here, but people as this guys and others try to assume things and judge without knowing. But its fine . for him to get angry like that easly surely he is not in good vibes and I which him the best 😄
!learn
I couldn't care less about Java, this is Unity and C#, my previous statement still stays
makes sense.
I am unable to use shortcut keys to comment out code
if they had actually learned java as they claimed they have, then they would know how to call a method on an object. and they would understand how types work.
C# is basically just microsoft flavored java afterall and most concepts apply to both
Why are you unable to use shortcut keys?
not really a unity issue. check your settings in your IDE 🤷♂️
That's also true
That is why I completed a 200h unity course now, but was not enough it seems. And if after 200h course and days trying to do something not enough to ask questions here.. this chat should be calloed Code-medium to advanced. If for me to be a beginner means to have almost 1000h course in videos, its fine I will be back here in 1000h videos and hope people dont judge me and are willing to help.. actually a lot are willing to help.. I just dont understand why people bother saying stuff to me if they dont want to help.. just dont say anything and let people that really want to help.. help as @eager elm just helped me some minutes ago and fixed my prob in 1 answer while others sent me 1000 answers with no help and just judments .
Gruhlum helped you because they gave you the code to write
yeah but now I understand what was the prob
I see the code, and the connection.
and BUM i know what I did wrong. next time I know how to do it.
It's not about the length, it's about the quality.
Not saying that the course you took was trash, but as we can see it missed quite a few important beginner details... so you could still learn something from the official website as a few people already suggested
Not answers like go watch 700h video or pseudo code that for a beginner is not easy most of the time to get it. and if 1 beginner gets faster than others, that makes us humans.. being dif
You need to learn how to translate words into code on your own, this is extremely important
my animated object isn't animated in-unity, so it seems it technically is not moving (if I select it during the animation, the xyz gizmo thingy stays in place while the object is moving around).
so parenting seems to do nothing
Having the basics is pretty much required to tackle a complex framework like Unity. That's why you either learn C# alone then switch to Unity, or go through Unity Learn that will introduce you to the basics of C# in a Unity context
No one forces you to watch 700h videos. There's the Unity learning courses which will take you a few days to complete, I learned a few useful things there even after ignoring them for the first year of working with Unity. There's also the documentation for quick examples of how to use things which you might need
Completing a 200-hour course that in terms didn't teach you anything means that either the course was way too advanced for you, or you did not reproduce what they did in the course enough to integrate it in your brain, or you did not pay enough attention
you're gonna need to provide more context. and probably also ask in a relevant channel since this doesn't really seem like a code issue
hello again, i had gotten to this part of the learning section, and hes not moving, my character is still at game play
does anyone know how to fix it?
Your game is paused
and the CC component is much lower than the mesh
So now I need to be afraid to use the community as I dont know if the answer will be a help answer or just a watch 750h videos. How can I know if the question I have is suitable for this channel? sad.
It will be a "watch a tutorial" for as long as you don't do so, or not have the basics in mind
Not sure what you should be "afraid" of either
It's not your questions that are the problem it is the answers you are expecting. If you expect answers to be in the form of 'here is the code you need' then you are, indeed, in the wrong community
Ok, understood now. Thank you
People are here to help, not scare you away. You think you're "afraid", but you're just misinterpreting the kind of help we give out here
We don't give you code that just works, we help you with your existing code only
So as you can see there's two colliders on the rat, one at the top, one to the side, and the cat clearly touches the top one first while jumping on top of it, which means the the rat object should be destroyed cus thats what i did with the script, and it cant collide with the other collider anymore. But the cat is touching the second collider as well thus loading the gameover scene, so how can it touch the second collider if the first collider destroys the gameobject?
collision messages will be sent to the parent rigidbody. if the script that loads the game over scene is on the parent object then it's OnCollision method will be called too
what do i do?
Ok, so lets try again. As per documentation, as per google and even other sources, if I use a scriptable object and inside of it I have this variable cs public Color color; I should be able as per image to change the color of the sprite. When I instantiate 2 dif enemies it is getting correctly all the other variables and its working great. But the color even being dif is not being applied. This color doesnt overlap the prefab color? It is using always the prefab color and not the one I choose in the SO, even tho all the other variables are working great in those 2 enemies. just the color is not working.. both have red color, even they acting dif with dif speeds etc.
does anyone know hwo to get this character model moving?
I did all of the instructions needed
and he doesnt go
"spacesuit"
It is using always the prefab color and not the one I choose in the SO
How are you assigning the color in code?
And this lacks a visual example of your enemies using the same color
https://hatebin.com/rwfhuizfje Hey all. I have this script that is responsible for my character to jump. When the player is on the move and it tries to jump. The forward velocity gets interrupted somehow and its almost in a stopped position. How can I fix this?
Vector3 velocity = Vector3.up * _jumpPower;
_rigidbody.velocity = velocity;
This kills all velocity that it had, and just overwrites it.
So you simply go up, and then start to get more velocity again because the other code is adding to the velocity.
So instead of overwriting, add a jumping velocity to it.
whats the best way to have tight character controls?
i dont remember if i asked previosuly but i haved tried manually settign the velocity and quite a while ago i also tried using drag
but im noot sure what the implications of this would be (glitchy behaviour, hardships of managing, etc) because i want to make an actual game worthy of publishing but im still pretty much a beginner and not too used to proper development processes
I am assigning the color to them. When I start the game. They are invisible in the scene even being spawned. If I click on the in the hierarchy the color there is correct, but they just dont appear. If I remove those lines on the SS they appear in the scene but with red color that is the color of the prefab and no the one I changed in the SO script
All right I will try thanks.
Well they won't show up since your color is invisible
Full black = no alpha
OH, I didnt know thre was a bar to control opacity there.. thank you that fixed the prob
https://hatebin.com/szghioplup Okay I added instead of overwriting. Now I get faster continuosly.
Jump seems fine.
Hello there, I am building a multiplayer game where I need to display players avatars in the game, so I made this ImageDownloader class :
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class ImageDownloader : MonoBehaviour
{
private Texture texture;
public Texture downloadedTexture => texture;
private System.Action<Texture> onDownloadComplete;
public void Download(string url, System.Action<Texture> onDownloadComplete)
{
this.onDownloadComplete = onDownloadComplete;
StartCoroutine(GetTexture(url));
}
private IEnumerator GetTexture(string url)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
www.SetRequestHeader("Authorization", "Bearer " + GameManager.Instance.authorization);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("Couldn't download image from " + url + " (" + www.error + ")");
}
else
{
texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
if (IsTextureSizeTooLarge(texture))
{
texture = ResizeTexture(texture, new Vector2(512, 512));
}
onDownloadComplete?.Invoke(texture);
}
}
private bool IsTextureSizeTooLarge(Texture texture, int thresholdWidth = 512, int thresholdHeight = 512)
{
return texture.width > thresholdWidth || texture.height > thresholdHeight;
}
private Texture ResizeTexture(Texture source, Vector2 newSize)
{
Texture2D resizedTexture = new Texture2D((int)newSize.x, (int)newSize.y);
RenderTexture rt = RenderTexture.GetTemporary((int)newSize.x, (int)newSize.y);
Graphics.Blit(source, rt);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = rt;
resizedTexture.ReadPixels(new Rect(0, 0, newSize.x, newSize.y), 0, 0);
resizedTexture.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(rt);
return resizedTexture;
}
}
However when I try to download and display large images (like 3000x3000) it freezes the game for a short time, less than a second I would say (It drops from 100 FPS to 15). I thought using a coroutine would prevent this issue but it doesn't seem so. Using the profiler shows me the following. Is there any way to prevent that? Using a background worker or something?
Of course, you are simply adding more velocity each frame without a cap and probably too little drag:
_rigidbody.velocity += transform.forward * _moveSpeed * Time.deltaTime;
how can I prevent this? maybe using clamp?
Well to be honest, the drag doesn't matter much when you force the velocity this way I think. Unsure about that part.
Yeah, clamping is possible.
- Coroutine still executes on the main thread. It can just help you break down complex processing into several frames. But in your case, there isn't much to break down. Half of it seems to be resizing the texture, while the other half is creating new sprites and stuff. Maybe you can break these 2 things into separate frames.
- From what I can see your player loop is already busy enough without that coroutine. It only takes 13 ms out of 32. That means that without it your player loop is 19 ms, which is already lower than 60 fps. Might want to optimize your player loop in other places too.@silk citrus
i feel like you probably need to look into Jobs, or try to do this Async, so that this can just be running in the background
Most of the stuff that takes time in their screenshot is unity api that can't be run from a background thread.
i agree with your approach
i think it needs to be taken off main thread
and if that operation needs to run all at once, then you need to break it up
yeah I think I have to fix my "hack" for making video players to work on webgl. I have to start playing a separate video and audio and sync them, currently every 0.5 seconds
thanks I will try looking at the documentation 🙂
Not sure how that's related to the problem at hand...🤔
Jobs let you split things into separate threads. Async lets you get off of coroutines, which need to get run alongside unity’s main thread
well that may slow down the PlayerLoop, maybe 0.5 seconds interval is too fast
what
Also, just FYI, you are using Time.deltaTime in FixedUpdate. This will make your movement different at different FPS. You should use fixedDeltaTime instead.
{
while (!videoPlayer.isPrepared)
{
yield return new WaitForSeconds(0.5f);
}
isPlaying = true;
while (isPlaying)
{
if (Mathf.Abs((float)audioSource.time - (float)videoPlayer.time) > syncThreshold)
{
audioSource.time = (float)videoPlayer.time;
}
yield return new WaitForSeconds(0.5f);
}
}```
Ah all right. Thanks
i thought Time.deltaTime = fixedDeltaTime when in fixed update?
it is
then Mr Jackson’s point doesn’t make a difference
Uh, its not? At 240 fps deltatime is 1/240, and fixedDeltaTime is 1/50
Or am I wrong on that part?
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
When this is called from inside MonoBehaviour.FixedUpdate, it returns Time.fixedDeltaTime.
They can't use jobs or threading async for their task anyway, as I said.
i mean that when you are inside of the fixedUpdate loop, deltaTime is set to be equal to fixedDeltaTime
My apologies then, ignore my comment.
it’s better to write fixedDeltaTime for clarity, but is not needed
Not sure how that slows down the player loop.
by running too often? I'm a beginner, that's why I chose this channel, I'm not saying that I'm right 😅
There's basically no processing done in that coroutine. Also that's not how "slowing the main loop works". If you yield for fixed periods like that, you'll just get spikes of lags(if there was anything that would cause them anyway).
I get that you're a beginner, which is why I'm trying to correct wrong assumptions. If you actually need help with anything, then provide more details on the issue and what you actually trying to achieve.
I'm not very familiar with coroutines concept, I thought that was implicit. I'll try looking at a better way to sync those video and audioclip components.
I just showed what I assumed to potentially takes the other 19ms of the playerloop, I'll try searching for a more optimized way to do it before asking for help about it 😉
quick question: what is better/more efficent:
- public variable
- private variable but changeable with a public function
2 is better. Could use a Property too.
most of coders prefer two
but if the setter is just setting the property then there is no different and i would just make it public
ok
typically all fields should be private and you should only expose your variables to other objects through properties
what do you mean through properties?
i just dont understand what is the different between:
public int a;
vs
private int _a;
public set_a(int a){_a=a;}
public get_a(){return _a;}
```apart from a additional function call
the second is pointless since properties exist
properties is compiled to some code likes second one
but it's typically about hiding implementation details and allowing you to change how those methods work without affecting the outward facing api
did you read the page i linked?
not 100%
but they ar get and set and stuff
but you have to do them by yourselves dont you
what do you mean "do them by yourselves"?
ofc if
public set_a(int a){_a=a;some other codes based on the new value of _a}
```then you should use setter
public int MyInt { get; set; }
that's a property
it's an auto implemented property with a compiler generated backing field. but you can use a full property if you need that. all of this is described in the page i linked
not default, since you can change the getter setter body
https://hatebin.com/wrgujvmfmr Why is it that when I spam space. Sometimes the jump sound plays twice even three times.
Like all code, you need to write it yes. Too bad, but the compiler can't read your thoughts yet. 😄
i dont understand are properties there or do you have to code them?
Wdym?
idk
Properties are a language feature. They have a certain syntax.
It's like askind "are methods there or we need to write them?"
Of course you need to write them lol
so you can just write "get var" in every script and get the public value?
why if is not in blue like it
I'm still not following. Mind providing an example with code?
huh?
i have no idea how to use them
i hear properties for the first time
The link boxfriend shared explains how to use them.
getter setter is syntax sugar
private int a{get;set;}
```is
```cs
private int _a;
public int a(){return _a;}
public void a(int _a){this._a=_a;}
Also:
#💻┃code-beginner message
you access and use them from other objects just like you would a variable
because my character doesn't jump so I wonder if it comes from
ah so its just a tool that c# writes these functions for you
i don't even understand wtf you are asking
auto-implemented properties are like a "more secure" way of exposing a variable
Right?
What tool? It's a syntax. You know syntax?
no not tool
i mean
im not a native speaker
you know what i mean
it just does it for you
are you asking why the syntax highlighting doesn't match exactly? if so, it's likely just a matter of the theme and has nothing to do with why your jump is not working
Does what for you?
it writes the functions for you
I want my character to jump but it doesn't work there is a problem in my code
It doesnt do it for you. Its just calls the getter and setter when needed, but doesn't write any function
the reason your jump doesn't work is becaus you are using GetButtonDown inside of FixedUpdate. GetButtonDown is only true for teh first frame the button is pressed which most of the time is not a FixedUpdate frame
yeah but the getter and setter are pre defined functions right?
You can modify them
{
get
{
// your own implementation
}
set
{
// your own implementation
}
}```
So they are not predefined
It compiles the property as a getter/setter method, yes.
You'd be surprised how much the compiler does for you. Probably things you don't event suspect. But that's getting into low level implementation.
but why does it work for him when he put it in
probably because the person who made that tutorial changed something in their project settings and also doesn't know wtf they are doing
ok thank you i think i understand it a little bit more now
Any idea why my jump sound plays two even three times when I spam spacebar? https://hatebin.com/zdtizsgofq
idk if 0.1f in checkshpere is small enough
but if the velocity is not fast enough, in the next physical frame it may return true
Hmm I should play with the checksphere's size?
made it .08 but still getting the same result
smaller than that would break the ground check
Might want to have sort of a state machine. { Idle, Jumping, Falling}
You only play the sound when you transition from Idle/Falling to Jumping.
are the player colliding with the ground? i think on collision enter/exit can be used for ground check
or if velocity change from (around) 0 to positive value then set the state to jumping
I solved it by doing as you said. It seems to be working fine now. Made the checksphere smaller. Then dragged it a bit more below the player.
Guys, I made a model in Blender, and I want the character to blink, but the thing is the eyes are part of the texture skin, is it possible to make the texture animated for opening and eyes closed? Or should I just make the eyes a 3d model and animate them open and closed?
It is possible with both ways, swapping textures (or materials) or animating it
Which one causes the least lag?
I doubt any of this will cause any 'lag' that you should be concerned about
3d animating the eyes could mean a few things too. Like is it an anime character or realistic or what
Profile it and see
the answer is probably "neither" if you don't have hundreds of characters on screen
I'm following a tutorial about a save and load to json system but I'm changing it so it saves classes instead of individual variables so it's more organized, I swapped from JsonUtility to Json.Net and tried to do this:
[System.Serializable]
public class GameData
{
public InventoryData playerInventory;
//set initial values here
public GameData()
{
this.playerInventory = new InventoryData();
}
}
which gave an error because InventoryData is a monobehaviour so you can't just make a new one without putting it in the scene somewhere, I'm wondering if anyone has an idea to still do something like this without turning the InventoryData into a normal class.
make inventory data a plain c# object. then pass that to some inventory monobehaviour
that also works I guess, thanks
Why does InventoryData need to be a monobehaviour
I thought that would be the easier way of doing it
but making an inventory holder should be fine
You might make a MonoBehaviour for a component that talks to an inventory
e.g. a chest would have a Container component that has logic for interacting with the container
but the inventory itself wouldn't need to be a unity object
I have been trying to get a simple plane with multiple vertices in my game. The thing is that the primitive plane doesn't have a parameter where you could adjust the number of vertices.
I tried looking for a solution on the internet, but it is impossible to find an easy solution.
Any ideas?
Probuilder
Except I'm broke
You can't afford free?
Too broke for free. Need something that would also pay money for using it.😅
I'll look into it again
#🛠️┃probuilder has resources pinned in the top right there btw. The video is a nice way to get a look on what it's capable of.
Do i animate my character in unity or in blender? I made a character in Blender and it's fully rigged. It will just act as npc and have an animation. What's the best way to do this?
blender
Technically you can do it in either place. But Blender's tools are much better.
Thank you! 🙂
I would very much suggest following Imphenzia's tutorial (the low poly cop thumbnail one) that includes the steps for creating necessary NLA strips and exporting the .fbx files from blender to unity properly.
helped me a ton when I had zero experience with working between blender and unity.
My play button is Way too big, how do I small it down? Because now even when I click on white surface it activates
Make it smaller
Any idea why these bullets slide on the wall instead of bouncing? https://img.sidia.net/ZEyI5/bupUcoZI90.mp4/raw I apply a velocity + no gravity, on hit they get gravity
Show code
BulletView.cs
private void OnCollisionEnter(Collision other)
{
Rigidbody.useGravity = true;
}
PlayerShootingSystem.cs
namespace InfinityShooter.Shooting.Systems
{
public sealed class PlayerShootingSystem : IExecuteSystem
{
readonly Contexts _contexts;
private readonly IGroup<GameEntity> _group;
private readonly List<GameEntity> _buffer = new List<GameEntity>();
public PlayerShootingSystem(Contexts contexts)
{
_contexts = contexts;
_group = _contexts.game.GetGroup(GameMatcher.AllOf(GameMatcher.Player, GameMatcher.Shooting));
}
public void Execute()
{
if (_group.count <= 0) return;
foreach (var playerEntity in _group.GetEntities(_buffer))
{
var nextShot = playerEntity.hasNextShot ? playerEntity.nextShot.Value : 0;
var currTime = Time.time;
if (currTime < nextShot) continue;
var bulletEntity = _contexts.game.CreateEntity();
bulletEntity.AddPosition(playerEntity.position.Value + Vector3.up);
var rotation = Quaternion.Euler(0, playerEntity.rotation.Value, 0);
bulletEntity.AddDirection(rotation);
_contexts.game.Instantiate(Res.Bullet, bulletEntity);
playerEntity.ReplaceNextShot(Time.time + 0.05f);
}
}
}
}
Nothing else in bulletview should be relevant, if you really want i can show the whole thing but its unrealted stuff
You might want to manually apply a bounce force. I'm not sure if changing useGravity causes the velocity to reset. It might be interfering with the Physics Material
What was the math for bouncing of a surface again? DotProduct of surface normal and object velocity?
You don't need to do the math, there's a function for it:
https://docs.unity3d.com/ScriptReference/Vector3.Reflect.html
Oh thats wonderful, thanks 😄
Adding a greater friction value on the bullets and/or the walls might help too
Had friction on both all the way up, it didnt really care for that
Bouncing it should be easiest purely just with physics, can you show the physics material?
https://img.sidia.net/ZEyI5/SAvIVEzA19.png/raw have this on both, had it on 1 on friction too for testing
Could try bounciness on 1 and change the bounce combine option to like maximum or whatever the options is
Although if you want to visually turn the bullet too then I guess it's easier to do via code. Let's you implement more like a max bounce
Using a different collider shape is one thing to try too
the bullet fizzles out after hitting the wall, i dont want a ricochet like thing
so i dont mind much about rotation, it can spin out for all i care 😄
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
(this step is required to get help here)
You also need to save the file
now it says this
check the method name of ienumerator
Hey, guys! I have a question. I have a background music on my Main Menu scene and when the player enters the game he is transferred to the title scene. I have functionality where it says under my Title Text Press any key to start so when the player left click one time,main menu scene is loaded. The problem here is that when the player enters the main menu scene and everytime when he left click the background music of main menu is playing repeatedly. So, what I want to do is to click and get to main menu scene only one time and when I left click not to hear it playing repeatedly. Is there a way to left click only one time and not to hear background music on main menu after left clicking?
{
// Initialization of some variables here!
public bool gameIsActive = false;
public bool isPressed = false;
public Button quitButton;
public Button playButton;
public Button optionsButton;
public Button pauseButton;
public Button continueButton;
public Button homeMenuButton;
// Start is called before the first frame update
public void StartGame()
{
gameIsActive = true;
Debug.Log("The game started!");
}
void Update()
{
PressAnyKeyToStart();
}
public void PressAnyKeyToStart()
{
if (Input.anyKeyDown)
{
SceneManager.LoadScene("MainMenuScene");
Debug.Log("MainMenuScene is loaded!");
}
}
public void QuitGame()
{
StartCoroutine(PlayAfterTwoSeconds());
}
IEnumerator PlayAfterTwoSeconds()
{
yield return new WaitForSeconds(0.5f);
Application.Quit();
EditorApplication.ExitPlaymode();
Debug.Log("Game quits and editor play mode stops!");
}
}```
Here is the script!
thanks 👍
i accidentally misspelt generate lol
I know already what causes the issue. I have PressAnyKeyToStart() on Update. So, that's why I am asking is there a pre built method or something to add on my script and add that method to the pre built method? Also, I have to note that I have UI Manager gamobject as a prefab on my hierarchy.
As if UIManager was persisted through scene changes, but that's not the case here
Yeah!
Scene loading happens at the end of the frame, so you're 100% sure that the if statement in PressAnyKeyToStart() is executed once. Unless:
- This script is present multiple times in the title scene
- This script is present by mistake in the main menu scene
The case here is that I have the method I said on Update() method. So, when the MainMenuScene loads it repeatedly after left click and every frame is playing the background music I have on MainMenuScene.
This is not an additive load so scenes will not stack
Note that when the Debug.Log("MainMenuScene is loaded!") runs, it's not actually the case just yet
All Updates will finish running for this frame, then the scene switch operates
I have UI manager script on every scene
Well there you have it, you will reload the main menu each time you press a key
I have it on every scene on my UI manager game object prefab
The "press any key" logic should be offloaded to another script that's only present in the title scene
I have made prefab of UI manage because I want to make every functionality of UI on specifically that script
@short hazel So, I have to remove UI manager script on my other scenes?
Let me see if that happens on other scenes as well like main scene
No, you do the thing in the message you reacted "👍" with
Oh, so I have to make another script separately for that functionality?
Can't I make that functionality work on my UI manager script?
No, and it shouldn't be the case
There is no other method for that?
Something that's used once must not be put in a script that's used everywhere
Alright then thanks 🙂
Apart from complexifying the code, and requiring you to modify the Inspector of your UI manager in each scene, the best method is still to use a separate script
I have an entire component whose sole job is to be the "press any key" screen
i need to mark that "last selection" field as non-serialized..
So, when you are working on a project what do you prefer to do making one script to handle all your UI functionality for example or making different scripts for different things? I think you will say depends on the situation you have. I love making things on single specific scripts for example when I have to handle UI to make UI manager for all of that when I have Audio for example different SFX to be played or background music etc to have an Audio manager.
I have an InterfaceController whose job is to turn on and off various interface components
a HUD, a set of game menus
the "you died" text
It would be a giant mess if all of those were literally just one script
The day I figure out a solid Unity workflow will be the day ❤️
hi, I created a public void that allows me to damage my character, but when I use it in another script it says it "does not exist in the current context"
I thought that's what public was for?
clarification
you created a method
the method is public, so any class can see it, and the method returns void (so it returns nothing)
Show the relevant code.
both the definition of the method and the place you tried to use it
public is for making it accessible from another class. You still need a reference to this class in order to call it, and to call it ON said reference
it doesn't mean "you can now just use this everywhere willy nilly"
Am I correct in thinking that there is a way to limit where you can move the mouse onscreen? (not cursor locking) More of a limited region of the screen where the mouse pointer can go?
You can't lock the OS cursor to a region, but you could pretty easily lock the cursor entirely and use the mouse deltas to move a fake pointer around the screen that you could do whatever you want with
What do you want to do?
How do i check if a gameobject has a certain script?
okay
if (!foo.TryGetComponent(out SomeComponentType _))
{
}
you can use _ to discard the result, since you don't care about it
Even out _!
oh, you can omit the type for a discard?
You'd need to add the type in <> then though
Hey, guys! If I want my background music of my main menu scene to not play repeatedly after the load of another scene for example I want to go to options scene and I have the same backround music that is playing. So, I want that music to be played continuously. Is there a function to make it work without loading the music again and again?
it needs the type either from the generic parameter or the type of the out parameter
@polar acorn@swift crag okay, basically. I have a plane on the ground receiving a raycast, my character then targets the raycasts hit.point. I'd like a decent solution to 'locking' the cursor to a specific region, but my current solution sucks bottom. lol.
idk if it really treats it as a discard when you specify the type name in the out param? Will check
I would just remember the last valid point you targeted and show a little indicator there
The actual scene........
The mouse cursor will still move around freely.
Imagine trying to move the cursor to the top right corner. If it couldn't go out of bounds, you'd be forced to move it left, then up
Yeah, I've been turning the cursor 'off' when it leaves the bounds of the plane object, but it looks horrible (character just 'locks' up and then 'snaps' when the mouse comes back in.
you could find the closest point that's still in-bounds (realtively easy for a plane, I'd think)
Yeah it does, use whatever
I'll take a look tomorrow. Had enough of it for today. Bit of Particle Play for a bit I think. lol.
raycast to the plane, then clamp its X and Y coordinates based on the playable area's size
Can you guys help me with this? I have a problem that my bullets don't always spawn in the same spot on the sight as you can see in the video.
Here is the code (I was trying to get the bullets to come out of the gun but focus on the raycast): ``` private void Shoot()
{
// Create a ray from the camera going through the middle of your screen
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
// Check whether your are pointing to something so as to adjust the direction
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(1000); // You may need to change this value according to your needs
// Create the bullet and give it a velocity according to the target point computed before
var bullet1 = Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation);
bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;
}```
sometimes like happens on the video the bullet is generated down of the screen or far where is pointing the raycast
well the bullets get instantiated at the muzzle object's position. so take a look at where that object is
also that code is suspiciously GPT-like
bot writes more comments than I do in a single script than I do for my whole project
Hello, I have a problem regarding sprites. I have a character that is made up of several sprites. all with the pivot below and in the center, all MUST be in Order in Layer 2.
This is because the game is a top down game and the camera orders everything in Y, and thus there is depth with the other objects, and if each part of the body has different orders, that would complicate things for the camera.
So, what do I do to be able to tell the game which character sprite should go first? Any way to do it through code?
Uh, I think those layers are subdivided, such that sort layer 0 is the first layer, but then the layer numbers is that of the specific layer
you know you can also use other sorting layers, right? then you can adjust the order in layer for each individual sprite on the layer
also not a code question
Can make it a coding question if you want to code in your only sorting layer manager ;)
basically it's just changing the z-depth by minuscule numbers
But if I use another layer of classification won't it make the character above or below everything else in the environment?
what do you think the order in layer does?
it's the same thing, but within a specific sorting layer
It's top down, sorted by and, and if you try it, it will work.
In the part were the gun shoot duh xd
And here what happens if I put the clothes and the hair in layer 3, and the body in layer 2. The body does follow the top down system, since all the other objects are also in layer 2, but the hair and clothes they ignore it and put themselves on top
oh yeah, my mistake! here i was thinking that the muzzle object's position wasn't being set in the code you showed. silly me 🙄
this is still not a code question btw.
(When it should be like this)
Which channel is for this? xd
So do you have any idea? I making the bullet to go from the gun to the crosshair
they aren't going from the gun. they are going from the muzzle object. where is that
In the point of the gun you know like all shooters
not in the center of the body of the player
Or the camera
and have you bothered actually paying attentiont to where that object ends up the times that the bullets do not fire from the gun?
because that is my whole fucking point
So the a viable option is to make the muzzle pointing by rotation to the crosshair?
what?
i'm telling you to pay attention to where that object is when this issue is happening
https://img.sidia.net/ZEyI5/ViloWIna61.mp4/raw works perfectly now, finally got back to it
private void OnCollisionEnter(Collision other)
{
if (_hit) return;
Rigidbody.useGravity = true;
var dir = Vector3.Reflect(_velocity, other.contacts[0].normal);
Rigidbody.velocity = dir.normalized * _contexts.config.gameplay.WallBounceStrength;
Rigidbody.rotation = Quaternion.LookRotation(dir.normalized);
D.raw(new Shape.Line(transform.position, transform.position + dir.normalized * 4), Color.green, 2f);
D.raw(new Shape.Line(transform.position, transform.position - _velocity.normalized * 4), Color.blue, 2f);
_hit = true;
}
Ill reduce the bounce and let it spin a bit and that should work for fizzling out then 😄
this only happens when the player moves
or when i spam click the gun
okay. so have you looked at where the muzzle object is when those things happen?
it's in the same place correctly but I'm worried about this piece of code var bullet1 = Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation); bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;
can someone help me with the input third person system, I have a lot of it done, but he doesn't run?
Please post your code and tell us which part of it does not work
all the code isn't at error in the scripting part
i can show screenshot of what it is set to though in the inspector
yes please show everything relevant, we cant help you without any context
So when you press buttons nothing happens?
yes
You mean the code that spawns the bullet at the location of the muzzle object and launches it toward the targetPoint? Why would you be worried about that piece of code unless the muzzle object isn't where you are expecting it to be?
I mean I don't know what the problem would be that the bullets sometimes aim at the crosshair but are not generated in the correct position
Because the muzzle object is not where you are assuming it is
Is your MoveComposite used anywhere?

