#💻┃code-beginner
1 messages · Page 396 of 1
Oh true
You can ctrl-a tro select all log entries and copy them
ya, that looks okay.. ur gravity is increasing
it does make a very larger blob of text
i wrote an editor script that prints the console into a .md as a list
so when isGrounded becomes false, the velocity starts changing
damnit.. i downloaded it
-5.00 is already plenty to cause a movement with the default minimum move distance of 0.001
you'd have to have a framerate of like
5000
for that to be a problem
(if your downwards velocity is very low, then you won't move at all, and isGrounded will become false)
oh, i found his code link sorry bout that @slender nymph
lol so should i make it more like .1
ah
what happens if u set ur isGrounded at the end of update loop
I am not (its at 60)
instead of at the very beginning?
ill lyk
lets go
Goated
😉 i had to do the reverse on mine
put it at the top instead of the bottom. weird how that works
So I guess the issue was with when it ran the first time
that shouldn't have made a difference except for maybe the very first frame
that doesn't make sense, yes
unless you were destroying and creating new characters regularly
there's only one CC.Move call in there. unless they have some other component calling CC.Move somewhere the only time the property should change is that one time they call Move
i normalized my input but now theres a delay for the character to stop moving
everyone saying it doesn't make sense.. thats exactly what i thought when my groundcheck was broken.. and i moved it from the bottom to the top..
you're probably using GetAxis instead of GetAxisRaw
something to do with the way the logic is writen
change it back then change your log to this and show what it prints: Debug.Log($"Velocity {movement}, Was grounded: {isGrounded}, Will be grounded: {controller.isGrounded}. ({GetInstanceID()})");
the entire point is that you check if isGrounded got set to true last frame
so that you can decide if you're on the ground or not
Could also be with the initialization like it started as true but now since its after it starts as false?
i renamed my variable even to wasGrounded
i see, whats the difference?
if yall can fix it w/ it at the top of the update.. i'd love to watch and see how ¯_(ツ)_/¯
if you access characterController.isGrounded before you call Move, you're asking if you were grounded last frame
Also of not the character doesnt start on the ground
if you access it after calling Move, you're asking if you are now grounded this frame
GetAxis applies input smoothing, which is why you have that short speed up and slow down. GetAxisRaw does not apply any input smoothing
ya, i have a landing mechanic.. as u can see headbob.CamRebound();
soo it makes sense for mine to be wasGrounded
but.. if i put the isGrounded/wasGrounded at the end of the update.. where it would make sense.. it doens't work correctly
i get an issue very similar to his
@slender nymph (this is with me not moving at all)
yeah that is one of the worst ways to share logs. i'm not downloading that
where
something else is affecting it because it isn't true in the frame after Move is called and the CC sees that it is grounded
Yeah this is it when its at the end instead
if you're going to change it at the end of the Update method then you need to do so after the log. otherwise you aren't actually seeing the value you are using but the value that it is being assigned to at the end of that method
or rather you aren't seeing the actual grounded state of the CC. because something else is affecting it
@keen pecan magic, i can't explain it.. but my controller was once bugging like urs.. and changing where it was in the loop fixed it..
Oh true
but i tried to test now.. and mine works either way
Im starting to accept that lol
you very likely have some other code calling Move on the character controller
yea, acronex might.. but mine im sure of its only 1 instance, 1 move call
I do see the will be working here now
Im sure too I click on move and its the only thing that highlights
i might have reverse the name of hte bool
and the conditionals
ahh, i did.. that why mine works better now..
wdym it's the only thing that highlights? i'm obviously referring to other code, not just that one class
did you actually use the search feature in your IDE
I literally only have 1 script rn
Ye
So I'm not sure how to fix this issue. It properly detects that W was pressed and it makes my character move. The only issue is the loop doesn't just stop. It just seems loops the code underneath the keypress. I just want it to run once per key press so it doesn't fly off of the screen.
{
if (Input.GetKeyDown("w"))
{
yMove = yMove + 0.1;
Debug.Log("w key was pressed");
}```
public yMove = 0;
Just to note that
This code will run one time whever you press w
Except it doesn't seem to... it flys off of the screen
your issue lies elsewhere
And it continues to rise.
How many times does the message log
Once
So it runs once
correct. because this code runs once when you press W
So then why would the player keep moving?
Nothing in this code is related to player movement at all
You are adding 0.1 to a variable
Anything more than that would require context
I think I figured it out
This is the rest of the code. movement = new Vector3(((float)xMove), ((float)yMove), 0.0f); transform.position = transform.position + movement;
The transform.position + movment keeps looping so it keeps adding the movement value
I think
that's not "looping" it's just likely inside of Update which is called every frame
and you never reset your variables back to 0
also, is there a reason your xMove and yMove variables are doubles?
I wanted to have more control over how the character moved.
that is not a sufficient reason to make them doubles
you won't get "more control" that way
You can use numbers that aren't whole which allows for more control of the character though
And how do doubles achieve that
that still isn't a reason to use doubles when pretty much everything in unity uses floats and you have to cast to float to use those for your movement anyway. so why not just . . . make them floats?
Why does it matter? They both achieve the same thing
well for one thing it will remove the unnecessary casting
and you don't need a 64 bit float since you are doing literally nothing at all that requires that precision when a 32 bit float is just fine and what you need to cast to anyway
this is a code channel
I dont know what to change to make the quality better
floats also are numbers with decimals
But why would it matter? Why can't I use doubles? Why are they worse?
ty
at no point did anyone say they are worse. they are just entirely unnecessary here
So then, if they aren't worse, why does it matter?
you know what, fine. i won't help you since you clearly can't fucking read
no one said you cant. theres literally no reason to use it. Your precision is as good as the weakest link, using floats and doubles, floats precision is weaker. You are using floats no matter what because unity uses it
and being pedantic, yes it is worse. You have to cast everytime you want to use it in any unity context and its more memory
🤷♂️ this is an extremely weird hill to try dying on though. Just swap to floats
I was asking for help pertaining to something unrelated. If it causes me problems later on I'll fix it. I'm just trying to learn and I don't see how I "can't read." If it doesn't matter it doesn't matter and we can all just move on. There's a section in the rules that mentions not criticizing someone elses approach to a problem. Please try to follow the rules. It isn't hard. All it takes to follow Discord rules is a little bit of reading comprehension.
in that case you've done nothing wrong. your code works the way you expect because it is your approach to the problem. and since there's nothing you need help with you can go take your wild takes about having "more control" over your movement because you are using doubles elsewhere
They are double the space taken, they require cpu time to cast, and the additional precision is lost anytime you cast. Oop, missed a bit
You were answered for your original question though, so I figure that is why they went on with the other questions
🤷♂️ idk why they even asked why it matters if they ignore every reason on why it matters
i'm betting they barely know anything about c# and made the variable a double because they wanted to add 0.1 to it but didn't know how to make that a float
Happy?
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float xMove = 0f;
public float yMove = 0f;
Vector3 movement;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("w"))
{
yMove = yMove + .01f;
Debug.Log("w key was pressed");
}
if (Input.GetKey("a"))
{
xMove = xMove - .01f;
Debug.Log("a key was pressed");
}
if (Input.GetKey("s"))
{
yMove = yMove - .01f;
Debug.Log("s key was pressed");
}
if (Input.GetKey("d"))
{
xMove = xMove + .01f;
Debug.Log("d key was pressed");
}
{
movement = new Vector3((xMove), (yMove), 0f);
transform.position = transform.position + movement;
yMove = 0;
xMove = 0;
}
}
}
Great. You win. A+. Gold star. 10 points to boxfriend.
You are welcome for them telling you about your issue and helping you fix your code. Not really sure the reason for the aggression, but they paid you a large boon
#💻┃code-beginner message
Hello thats my first 3d project on unity and i tried to create a HP bar with a tutorial. I write the same line but it doesn't work. Someone can help ?
hello i tried to put my inputfield on the gameobject script but i cannot put it there like its refuse or not detect it as inputfield ui
Not a code question.
#📲┃ui-ux would be the right channel of course
you're probably using a TMPro.TMP_InputField but your variable is likely UnityEngine.UI.InputField
That page is more useless than my dad in my childhood. I found the problem
then you didn't bother reading the information it provided or the suggested solutions
its work, thank you
float mouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;
yRotation = yRotation -= LookInput.z;
yRotation -= mouseY;
yRotation = math.clamp(yRotation, -90f, 90f);
Neck.localRotation = Quaternion.Lerp(Quaternion.Euler(0f, 0f, 0f),Quaternion.Euler(yRotation, 0f, 0f),0.5f);
transform.Rotate(Vector3.up * mouseX);
transform.Rotate(0,LookInput.x,0);```
Hi. I made a camera script for my ``Character Controller``. How can I apply ``SmoothDamp`` to this code so I can smooth it all out when you rotate rather than just coming to a complete halt?
the ``LookInput`` is for controller support with Unity's new input system, I figured this was an okay method to apply.
don't multiply mouse input by deltaTime, it's already framerate independent so doing that multiplication makes the value dependent on the framerate again and leads to stuttery camera controls
taht is suspicious as fuck my guy
if you want to share your game, upload the entire build to a reputable site like itch.io or something. and share it in #1180170818983051344
i just conpressed these
i don't care. see #📖┃code-of-conduct
oh ok
or i guess the guidelines for sharing a project are actually here: https://discord.com/channels/489222168727519232/1180174978151358584
ima just delete it
thank you!! 🫡
I didn't know that. do you have tips regarding Smoothdampening with my current method by chance?
There's no Quaternion.SmoothDamp, unfortunately
However, your use of Lerp can be improved a bit
Lerping doesnt seem to do anything, it acts as if I dont really have one applied
You aren't using deltaTime at all in the lerp, so it's going to be ultra fast
ohhh
yeah, you're moving 50% of the way to the destination every frame
zoom
Read that page, though. It explains a better way to use Lerp
You can also mix in Quaternion.RotateTowards
That way, you don't slowly approach the target forever
you always move by at least a bit each frame
tf
I have my GameManager now, but when I try to change a variable in it (specifically, use a function inside of it that changes it), it gives me errors. If I print GameManager.Instance it gives me null. How do I fix this?
show the relevant code, including where you assign to GameManager.Instance
So the code that accesses it is this:
public class ControlPresetScript : MonoBehaviour, IPointerClickHandler
{
[SerializeField] public GameObject presetDropdownMenu;
[SerializeField] public Sprite wadSprite;
[SerializeField] public Sprite ulrzSprite;
[SerializeField] public Sprite customSprite;
public void OnPointerClick(PointerEventData eventData)
{
presetDropdownMenu.SetActive(presetDropdownMenu.activeSelf);
}
public void SwapPreset(int preset = 0)
{
Debug.Log(GameManager.Instance);
switch (preset)
{
case 0:
gameObject.GetComponent<Image>().sprite = wadSprite;
GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(0);
break;
case 1:
gameObject.GetComponent<Image>().sprite = ulrzSprite;
GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(1);
break;
case 2:
gameObject.GetComponent<Image>().sprite = customSprite;
GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(2);
break;
default:
gameObject.GetComponent<Image>().sprite = wadSprite;
GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(0);
break;
}
}
}
And the relevant code in the GameManager is this:
public class GameManager : Singleton<GameManager>
{
public GameStuff gameStuff = new GameStuff();
public class GameStuff
{
public Controls controls = new Controls();
public class Controls
{
...
public void ChangeControlsToPreset(int preset, KeyCode customLeft = KeyCode.A, KeyCode customRight = KeyCode.D, KeyCode customJump = KeyCode.W, KeyCode customShoot = KeyCode.Space, KeyCode customSprint = KeyCode.LeftShift)
{
switch (preset)
{
case 0: // W A D S L-Shift
leftKey = KeyCode.A;
rightKey = KeyCode.D;
jumpKey = KeyCode.W;
shootKey = KeyCode.Space;
sprintKey = KeyCode.LeftShift;
break;
case 1: // Up Left Right 0 R-CTRL
leftKey = KeyCode.LeftArrow;
rightKey = KeyCode.RightArrow;
jumpKey = KeyCode.UpArrow;
shootKey = KeyCode.RightControl;
sprintKey = KeyCode.Keypad0;
break;
case 2: // Custom
leftKey = customLeft;
rightKey = customRight;
jumpKey = customJump;
shootKey = customShoot;
sprintKey = customSprint;
break;
default: // Default to W A D S L-Shift
leftKey = KeyCode.A;
rightKey = KeyCode.D;
jumpKey = KeyCode.W;
shootKey = KeyCode.Space;
sprintKey = KeyCode.LeftShift;
break;
}
}
...
use a bin site to share large blocks of !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.
Okay lemme do that
Notably, nothing in here assigns the instance
we'll also need to see that Singleton<T> class since it seems to be where the Instanc evariable resides
ah, yeah, that's where it'll actually happen
and is the GameManager component attached to anything in the scene? and where are you calling SwapPreset on ControlPresetScript
I don't know what you mean with "is the GameManager component attached to anything in the scene", isn't it enough for it to exist in the file system?
I'm calling the SwapPreset in my dropdown.
no, it is a MonoBehaviour which means it has to be attached to a gameobject for the Singleton's Awake method to run
I cant find out how to destroy other gameobject? i thougth it was destroy.Gameobjcet.Other but it isnt?
pass the gameobject you'd like to destroy to the Destroy method
Do I just have to create an empty object and attach it to that?
Okay
surely where ever you grabbed that Singleton class from explained how to use it? (i'm assuming you didn't write it yourself since you don't seem to understand how it works)
It works, thank you!
It does but I often don't intuitively know something that tutorials assume everyone knows. i.E. without being told, I didn't know that it had to be attached to a GameObject.
if it is a component then it must be on a GameObject to work correctly. and it is a component if it inherits from anything that inherits from Component. like MonoBehaviour.
if you are not familiar enough with the engine to know that, i suggest going through the junior programmer pathway on the unity !learn site. it will teach you the fundamentals (of the engine) in a structured, easy to follow manner
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Assigning sprite to Image, how do I do this?
[SerializeField] private Image itemSprite;
itemSprite = slot.Item.itemIcon;
public Sprite itemIcon;
this line: itemSprite = slot.Item.itemIcon;
needs to be inside of a method
also you need to assign the sprite property on the Image component
Hello! I am new to game development and have so far been trying to learn by doing some small projects. The problem is that I still lack a lot of knowledge to even make the smallest projects.
My question is if anyone knows of any good courses to learn C# in Unity? So I can become more familiarised with the language and get started working on my small hobby projects!
The Microsoft C# manual.
how do you use the third 'current velocity' parameter for smoothdamp?
ref and then a variable to store the value in. If you don't intend to use it outside of this function, just ref Vector3 whateverNameYouWant
well they would want it as a field to store the velocity over frames then reference it, method scoped would defeat the purpose unless its a coroutine
is the ref variable supposed to be a float? it wont let me enter a Vector3.
there are 2 smooth damps
you must be using the Mathf.SmoothDamp right?
if so use a float
Depends on which smoothdamp you're using. I don't know why I assumed it was Vector3 instead of asking
But it'll be the same type as your target variable
Just whichever type you want
when damps the movement of a vector the other the movement of a float
what are you trying to smooth a postion in space or just a value
okay okay that makes sense. i was smoothing a float value, so I'd use the Mathf variation
also where are you using it, in Update or a coroutine?
Update
cool, so i would make the velocity float be a field
why isnt lerpVar being used?
you only ever assign values to it and never read the value of it
what is your intent, noticed you are passing it in as well, are you expecting this function to adjust the field f as it runs?
yeah i want to change f
also that, if you only ever want to do it via f and not anything you pass in
how to make the animator play should end first after proceeding to other method?
I animated my legs for a character, but one of the legs goes missing when I click play. Can anyone please help?
Did you check under the bed?
But seriously, you should share some more context and/or video or screenshot demonstrating the issue, as it's not entirely clear from your explanation.
my attack state doesnt have animator run in it ony attack
but when i check to the animator nodes it is transitioning to run for a second then go back to attack again
why is that?
@teal viper UPDATE: I copied an animation from one leg to the other but when I click play, the other leg disappears. How do I copy animations?
not quite sure if this is the right spot, but I'm having problems saving. Whenever I press the button to save or load it just says "object reference not set to an instance of an object" (Error attached)
the options code is the only one attached to an object, and save and load are called from a button referencing the object with the options script. All the other save scripts are static.
A second ago it was giving me another error but it's just mysteriously stopped even though I didn't change any thing
Hey, always look up the error or general error before asking around, that means that something that you have tried to call doesn't exist according to the code. On the error, it says the problem is at line 61, look around there
There no reference on line 61 that doesn't exist tho, it references another script which is static
the reference exist, but for somereason isn't recognised
I don't know too much about call errors, but the error says otherwise, have you tried double clicking on the error
it should bring you to the line of code where the problem is
Hey, I got a problem with raycast detection. My raycasts are set in an array, 24 around a circular object in 360 degrees. I need to call upon each array and see if it collides with the ground, if it does, then it is grounded. That seems to work, as I get a Debug.Log() received, but the majority of the casts, being above ground, keeps isGrounded as false. code - https://gdl.space/iweminuyut.cs
NREs are thrown when you try to access a member like foobar.something and foobar is null. If volumee = data.volume; is line 61, then that means that data is null. Your Saving.Loadoptions() method returns null in two cases.
i want it so that the wall apperas as it is on top of the ground
any tutorial or blogs to read would be appriciated
So you want isGrounded() to be true if any one or more raycasts hits the ground?
no, if any single raycast is touching the ground, then isGrounded is true
Currently if more raycasts are in the air then isgrounded becomes false
okay, I've figured that out now. But I'm still not sure how to fix the problem. It needs to return something, and if it tries to return a Savedata class when the filestream is empty then it gets annoyed because theres nothing to deserialise. Is there a way I can tell it to not run the load if theres nothing in the file?
You could reset isGrounded to false prior to the loop, then only have a positive ground collision set isGrounded to true and get rid of the else. Alternately/additionally, if this is these raycasts only function, you could also break out of the loop at that point so save on physics queries - no need to keep checking them if you know you already know you're grounded.
Oh ok got it. Ill try that thanks
You could maybe just bail out of loadoptions() early if no save data was retrieved:
Savedata data = Saving.Loadoptions()
if (data == null)
return;
Thankyou! This works! There is a new problem though, lemme just screen shot the error...
If this is code related, you should share the relevant code. Otherwise, this seems like maybe something for #🔀┃art-asset-workflow or #🖼️┃2d-tools
yeah sorry i put it in terrain
It's happened again. This time I can't figure out what the problem is because it's ot calling or returning anything? line 21 just references one of the variables in options. It is also not the first time the sscript references a variable in options, so clearly the other variables are working fine.
The code for SaveData hasn't changed
If it's getting past line 20, then options can't be null. Seems like options.currentres is likely null in that case.
I am trying to make a sprite change to a random one, but currently I am setting it in FixedUpdate() meaning its changing the sprite 50 times a second. Does anybody know a way I could make the sprite change with a delay of my choosing?
why does my game play differently when i go full screen? My character moves slower?
how do i use MenuUI.GetComponentInChildren<TMP_text>(); to get the "TMP_text" part from "ButtonText"
Most generally you can use a simple timer (checking if it's time for the sprite to swap each frame, and updating the next time at which the swap should occur each time you swap), or use a coroutine. If you go the timer route, this should probably be in Update() instead of FixedUpdate(), as otherwise the sprite might not visually swap for several frames afterwards
Nevermind, I figured it out, thank you!
I copied an animation from one leg to the other but when I click play, the other leg disappears. How do I copy animations?
If you have multiple objects with TMP_text components in that subhierarchy, that could get a little messy/inefficient - I think you'd have to filter through all the results and test each game objects' name, which is also fragile as you would need to remember that if you ever change the GO's name you also need to change the name you're filtering for.
Ideally, if something depends on that specific TMP_text component, it would be better to cache a reference to it either where it's needed, or in some script responsible for controlling that UI. Cut out the middleman and directly provide the reference so that you needn't write code to search for it.
The easiest way would be just use a
public TMP_text ButtonText;
field in the dependent class, and drag the TMP_text component to it in the inspector.
K so I just manually set current res to the screens resolution and tried again and its still showing the error. So curretnres is not null and it's still doing it. I've been brainstorming for a while and I've no ideas.
I'm not sure how you've set it, but if the NRE is still on that res[0] = options.currentres.width line, then the only two possibilities are that res is null (which I don't believe to be the case - since it's a public field I think Unity should initialize it by default?), or options.currentres is still null there for some reason. You can of course test directly to figure out which is null:
if (res == null)
Debug.Error("RES IS NULL!");
if (options.currentres == null)
Debug.Error("CURRENTRES IS NULL!");
In the longer run, learning to use your IDE's debugger always pays dividends - it allows you stop code execution, step through it line by line, and examine all of the values of things in memory.
woah not me totally forgetting debuggin exists. Gimme a second hang on...
K so that didn work... do i test width and height manually? it just said that resolutions can't be null right? that's what that means?
okay so it says ints can't be null... so I can't test width and hegiht seperatly. Which i guess means currentres being null isnt the problem then?
I got it figured out and created an array with getcomponentsinchildren, thanks!
Resolution is a struct which cannot be null
Does res have any items in the inspector? Arrays in C# have a fixed size that can't change, so if you've specified no items in the inspector, Unity may be initializing an empty array by default, and it's failing to access res[0] as it does not exist. You may need to initialize your res array with a size of 2 (or more - or change it into a List<int> so you can leverage resizing)
aha! that's probably the issue. how do I declare the arrayu size in the code again?
wait it's just int[] = new int[] isnt it
public int[] res = new int[2];
it's not serializable anymore...
you have the wrong attribute on the SaveData type
what do you mean by that?
look at the attribute you've placed on the SaveData type. it should be Serializable
okay so uh.... this happened. I guess it wasn't deserialising before so it never noticed it or something? anyway, heres the error and the code in question.
you should not be using BinaryFormatter. it is a security risk
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
oh and another sharing violation but I'm guessing that's just causd my this error
okay... is that gonna completely change my code to fix? cause that's gonna be a nightmare
Thanks for telling me, I 100% would have kept using that forever otherwise
it honestly wouldn't be a huge change if you just switch to json utility or something, there should be plenty of tutorials for how to use that for save/load
How important is it? cause the game is only for a competition, it's not SUUUUPER important that it's safe...
well binary formatter can potentially allow malicious code execution on yoru players devices, especially if they share save files and stuff
... so in theory if it's only going to some judges who will almost certainly have a virtual machine running it because it would be silly not to, it would be fine?
anyone know the command to bring up the unity visual studio set up agaon?
it's linked in #854851968446365696
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
you know that embed was also in #854851968446365696 , right?
literally right above the one with all the commands
i mean, i guess
oh haha i saw the code and used it XD sorry
#854851968446365696 still the least read channel of the server smh
okay that's good cause i can NOT be bothered to change it when i need to submit this game in like 4 days and it's only half done
hummm ok weird so small issue the visual studio vode editor altho set up correctly. is claming that my void on update isnt used... i dont know why. im doing some mesh defromation at run time, and testing in the editor but it isnt working. idk why.
well where do you call OnUpdate?
i have a code related question i want to make a hord based spawning system over a random range over a 2d top down feild and idea how sould i go arround this?
like any like blogs to read or tutotials would be appriciated
you can use Instantiate to spawn an object, methods on the Random class to generate random numbers for the positions and the like, and a loop
its an event called by vrchat its the exact same as event update. but its just called from another script in vrchats sdk.
im asking in their servers as well but i dont know what i did wrong as that exact same code works in another project
if it is a message sent from the vrchat sdk then naturally vs code wouldn't see that you are using it. of course if you have problems with anything related to the !vrchat sdk, you can ask in their discord server 👇
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
ok guess im i cant ask here sorry.
your leg didn't disappeared it went exactly were you told it to if you copied the animation
the exact position & rotation unity doesnt have a flipped copy and paste like blender
you are better off making low poly test animations in blender and exporting them
or if you really need these animations to be in unity only
copy the X in your postion tab when the animations not playing
and paste it for it each frame
that should technically do it
I already fixed it by removing the position component.
ok quick question I'm about to work on a save system for me game is it possible to save DontDestroyOnLoad objects
you can save anything as long as it is serializable by the save system you use
alrighty thank you
hey i have a problem when i install unity and direct it to my E drive it takes memory from the C drive and when i install unity editor also directed to E drive it starts downloading in C drive
yes, that's where your downloads folder is
is there any way to not use C drive memory?
only if you really, really know how to modify your windows configuration. I would not recommend even trying because screwing it up can seriously break your computer
ok thanks
Quick question.
I have a situation where multiple objects fire a OnTriggerEnter event (Bullets entering an enemy object), and i have a problem with processing this situation.
Is there some way to look at all of them at once, like a list of currently triggering objects?
Or is there other good ways to handle that?
can i change size of player without affecting its circle collider.
So purely the visual sprite or mesh? Why would you not be able to do that?
Sounds like you have a different issue that is reason for this question?
its not a big deal. nvm
There are methods like this that can be used to collect colliders inside a given trigger. There are also variants for box and capsula and you can also have an alloc version that creates the array for you rather than supplying the method with one.
Maybe you can try this instead and call this each frame on your enemy
Not sure how much better this would be over just checking using the OnTriggerEnter method, though. Why would that not work here?
I have pickups spawning in my game by object pooling in which there are pools (list). I want to deactivate a certain pool from spawning for a specific condition. What do i do?
it fails (sometimes) when i count player score. Each hit adds a bit.
And when enemy object is killed, it adds incorrect amount of score. Sometimes more, sometimes less, but everytime that is caused by multiple sumiltaneous fatal blows. It's probably on surface and i'm just dum
here's code if you interested:
public void GetDamage(int dmg){
int prevHP = HP;
HP -= dmg;
int score;
if (HP > 0){
score = prevHP - HP;
}
else{
score = prevHP;
}
InterfaceSingleton.Instance.AddScore(score * 10);
if (prevHP > 0 && HP < 1){
Destroy(gameObject);
InterfaceSingleton.Instance.AddScore(500);
}
}
It fails to call the method? Did you try logging a message when it's triggered to verify?
if i get it correctly, all triggerenter events processed in some order, not simultaneously, so it should be fine, but it is not
I never heard it would not trigger
bad wording.
fails as in incorrectly adds score, not that it not fires. It does.
oh, i guess i got what's wrong
So as in a race condition? Code runs simultaniously and incorrectly updates an old state?
Because Unity is synchronous and that doesn't happen
I'm kind of confused on the root issue
How does it incorrectly add score?
I fixed that. Problem was that I did not check if prevHP > 0
At first it added more points that it should, because I didn't handled it properly, and now it added less for the same reason.
@burnt vapor big thanks anyway 
This is a code channel
why do i need to do SetBool/Trigger for animation booleans/triggers
and why do triggers exist
are they not just bools
They are two completely different things 
completely different?
isnt a trigger just a one way bool
also why is this needed
So you can transition animations
Another small question.
"yield return" in this coroutine just makes a while loop wait for some time before another loop?
private IEnumerator Coroutine(){
while(true){
sumCode();
yield return someTime;
}
}
incorrect syntax but, yes
Alright, that's what i wanted to know. Thanks 
kinda pseudocode btw
then you should say so, we are not mind readers
well, i tried to make a syntactically correct example that does nothing, but shows intention, but failed to do so i guess. noted.
thanks anyways
Yes, yielding essentially pauses your method. Note that you can create your own system outside of Coroutines as long as you return an IEnumerable or IEnumerable<T>
The point is the underlying enumerator (which coroutines use directly) that can be iterated in steps. That's also how Unity pauses Coroutines to simulate delays
Looks interesting. Useless to me for now, but i'll save a note. Thanks 
You could technically make a similar system like a Coroutine. Unity just does it themselves when you call StartCoroutine
my character is not collding with the tilemap. they have the same layer and the tilemap has a tilemap collider
but why is it different to boolname = true/false
Having the same layer is usually not that relevant unless you've messed around with the layer collision matrix
Show the inspectors of the objects you expect to collide
if a public variable is not being referenced from another script, but you need it to be public to reference something else, would it be written as "variableName" or "VariableName"
- tilemap
- enemy
my game also gets this error a lot but i dont think it relates to collisions
well what line of code does this apply to?
The latter (PascalCase), even though Unity uses the former (camelCase) as a standard. Do what you think is best, compliance with regular C# conventions, or Unity's
Because a bool is true or false and trigger isnt? Not sure what specifically you're confused about
oh okay
You can read the description
https://docs.unity3d.com/ScriptReference/Animator.SetTrigger.html
not sure what the point of a trigger is
its not like you would accidentally reverse the trigger
this one i think
So you can fire off an animation transition without having to manage the value of a bool. It's a one time call.
oh okay
so you can trigger it multiple times?
instead of flipping on then off then on again
Triggers auto-reset when the transition is consumed
Isnt this how you get the Rigidbpody?
so this gameObject does not have a Health script attached or data is null
is it a good idea when programming to use as many methods as possible
idk. it has a health script. im mainly just trying to fix collisions whihc should be working but its not
to make it look clean and to allow you to isolate the methods code
So Debug it to find out rather than just making assumprions
i dont knowhow to debug this is my first game
theres no code its just like the collision between 2 game objects
debug.log
thatt means i cant use unity becuase i don't have enough space
Yes it is one of the ways to retrieve a reference to a Rigidbody
Whether it's correct in your context cannot be confirmed though, but since you're posting this I guess something is wrong with it.
Always, if you have errors, post them in the original question
There is acctually no errors the Enemy just wont get its own Rigidbody...
If that was the case, you'd get a NullReferenceException
So either the code doesn't run, or it runs but the force is so small that you can't see any movement
It is what it is, what do you expect us to do about it?
Lol the force was to little. Thanks!
i mean when i install games they usually use memory from drive i directed it to but i understand
Depends on the installer. Some do that, and ohers download the required (compressed sometimes) files to the Temp directory (which is on the system drive) before unpacking them to the final install directory.
Some even require parts to be installed on the system drive, like Visual Studio
If the sum total of your Windows experience is installing and playing games it does not exactly equip you for a life in game dev. I would suggest you invest some time into learning how the Windows OS works
Wow, appreciate the suggestion. I am just saying if the thing isnt gonna download where i want then why give me an option i dont see why would anyone get mad, but its not only games its other programs. this conversation can end. appreciate ur time.
because it does not offer you a download folder selection it offers you an install folder. Download != Install. This is exactly what I mean by you need to learn
note that this has nothing to do with code
it's also not exactly a unity problem in general. free up some space.
it won't be permanently used; it's just where Unity keeps data that's being staged
oke, i asked cuz i didnt know but appreciate the honesty.
Why cant i use Random?
did you read the error?
yes
okay, so you know why you can't use Random, then
it tells you exactly what the problem is
huu?
'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'
What do you not understand about this error message?
I can't help you if you just make confused noises
What the diffrent is?
I have no idea what that's supposed to mean
'UnityEngine.Random' and 'System.Random' The diffrent between these.
Ambiguous is 4 sylables. Could it be this is difficult to parse for someone bought up on text speak?
They are two different classes.
one says UnityEngine, the other says System. You have to define which one you mean because the compiler cannot make the decision for you
Different things generally have different names.
You can clarify which class you want to use with another using directive.
And your question is?
not a code question #💻┃unity-talk
Also !learn has all the resources you need
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyDamage : MonoBehaviour
{
public wallHealth wHealth;
public float damage;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall") )
{
wHealth.health -= damage;
}
}
}
can any one tell
me what is causing this error
and how can i fix this
!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.
Follow the instructions above so the code is properly formatted
at Assets/Scripts/enemyDamage:25
Your error happens on line 25 of the enemyDamage script.
hi guys im having a problem but i dont know where is it im creating a game like vampire survivors and i have animations for all type of weapons and everything but the animation is not working on any weapon
Some variable on line 25 has no value (it is null), but you're trying to do something with it anyway
You changed the code and forgot to assign the script again. Drag-drop the object which has the wHealth script on it
ok
i want to assing a tile map to this to which a script is attached how should i do this
i want this wall to have health and if some one attacks it it looses health
So wouldn't it make more sense for the enemy script to get the WallHealth component from the thing it hit instead of one you drag in
it would how can i do that i am not good at coding would appriciate if u can point me towards the right direction
thanks ❤️
Hello, not sure where to put this as there isn't a channel for it. My Project won't update it's Player Version to file when I make a change (Project Settings > Player > Version). Does anyone know why? I have Project Settings as a submodule in Git and we use it to differentiate our software versions. Git obviously can't see a file change as there isn't one. Thanks
which file are you looking at?
also hit save project from the file menu after making changes to settings
also project settings as a submodule in git is very weird behaviour and way to set things up
that is...odd, yes
Hello guys, i have a problem with my gun system (2D). The gun works perfectly when i play the game for the first time. But if i reload the scene (pressing restart level button) i suddenly cant shoot the gun anymore, i need to restart the game and join again for it to work. By the way this only happens in the built version and not in editor. Thank you in advance
you would need to descrive more about how your reload works, and how that differs from how the game does it on first launch
and provide what errors you are getting when you try and shoot, feels like its losing reference
I dont change anything after pressing the restart button, it just reloads the scene
but the logs should tell you that
And i cant even debug because it doesnt happen in editor
sure you can
You can debug outside the editor
how
what platform is it
windows
By reading log files and attaching the debugger
basically all the same ways
or attach the console from the editor too it
how
can even attach your ide debugger if you build in dev mode with script debugging
do i open command prompt and type "gamename".exe
well easist way would be to just get the log file
where is it
%USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log
you will need to replace parts of that path based on your org and product name
DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.
it only has this error i think
You cannot make an object with a parent a DDOL. It has to be on the root object
oh wait
that way you only get stuff from 1 gameplay session
i got an NullReferenceException error
ok and look at where that error is, and figure out why
NullReferenceException: Object reference not set to an instance of an object
at GunShooting.Update () [0x00050] in <febfd361b8104404ba670889ca3da885>:0
at PlayerShooting.Update () [0x00000] in <febfd361b8104404ba670889ca3da885>:0
Is there a way to get the line
number
Did you build the game as a development build?
It should generally be pretty obvious looking at the code though for an error like this
A dev build would include line numbers. But you can check your GunShooting update and see if there's anything obvious that could be wrong
it takes a bit of work, but seeing the callstack should be able to get you close enough, also yeah make sure development build is checked
public virtual void Update()
{
if (!canFire)
{
timer += Time.deltaTime;
if (timer > 1 / gun.firerate)
{
canFire = true;
timer = 0f;
}
}
bool ShouldRotate = !(transform.parent.eulerAngles.z < 90 || transform.parent.eulerAngles.z > 270f);
foreach (Transform childObject in transform)
{
if (childObject.GetComponent<SpriteRenderer>() != null)
{
childObject.GetComponent<SpriteRenderer>().flipY = ShouldRotate;
}
}
}```
ok i will try doing a development build
probably gun is null
so would look into how those are defined
i dont think its null because i set it in the inspector
oh did not notice they were 2 difference ones since i would never do one just to check for null then do it again
well try a build that gives line numbers
and it will be very obvious
maybe your code is reassigning it
you;d have to show more context
or if this is DDOL it would lose references as other stuff unloads
bool ShouldRotate = !(transform.parent.eulerAngles.z < 90 || transform.parent.eulerAngles.z > 270f);
this line gives the error but its from a different gun object
that has no parent
well that explains it
If it's expected for you to not hav a parent sometimes, you need to make sure in your code that you heck for that before using it.
no the gun that has no parent doesnt affect it
its a different object
if ( (Input.GetMouseButtonDown(0) || (Input.GetMouseButton(0) && gun.isAutomatic)) && canFire && isPickedUp && !GameManager.Instance.isPaused)
this line gives a null reference exception too
Then either gun or GameManager.Instance is null
i dont know how they can be null
the gun is set in the inspector
add some log statements to check on thing and test assumptions
and the bug was there before i added gamemanager so it cant be null
why does it only happen in built versions and not in editor
NullReferenceException: Object reference not set to an instance of an object.
at CameraShakeManager.SetupScreenShakeSettings (ScreenShakeProfile profile, Cinemachine.CinemachineImpulseSource impulseSource) [0x0003b] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Managers\CameraShakeManager.cs:51
at CameraShakeManager.ScreenShakeFromProfile (ScreenShakeProfile profile, Cinemachine.CinemachineImpulseSource impulseSource) [0x00001] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Managers\CameraShakeManager.cs:39
at GunShooting.Shoot () [0x0003a] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\GunShooting.cs:31
at PlayerShooting.Update () [0x0004a] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Gun Scripts\PlayerShooting.cs:18 ```
it turns out that the guns shake profile gets deleted
for some reason
Hi! I am kinda new to unity. I followed a movement tutorial(using get axis raw input and moveposition) and then tried implementing dashing on my own via AddForce. This however doesnt work for me. I tested with a new script and it seems like my movement script "blocks" all Force functions. Why is that?
speed = GetComponent<stats>().speed;
position.x = Input.GetAxis("Horizontal")*speed;
position.y = Input.GetAxis("Vertical")*speed;
rb.MovePosition(rb.position + position);
is it 3d or 2d
2d
speed = GetComponent<stats>().speed;
float x = Input.GetAxisRaw("Horizontal") *speed;
float y = Input.GetAxisRaw("Vertical") *speed;
rb.AddForce(new Vector2(x,y));```
Because your code is just explicitly setting the position to an exact place.
Naturally with that code running, nothing else will be able to affect the object's position
That was my guess too but I can't think of a workaround?
try this
You can either change your dash code to compute the effect of the dash on the final position which will be passed to MovePosition(), use forces to move the character instead of MovePosition(), or disable the movement code while the character is dashing
Your workarounds are to change the way your movement code works, or disable that movement code temporarily while you dash
impulseListener.m_ReactionSettings.m_AmplitudeGain = profile.listenerAmplitude;
this is the line that gives me null reference exception error, do you know why?
full function:
private void SetupScreenShakeSettings(ScreenShakeProfile profile, CinemachineImpulseSource impulseSource)
{
impulseDefinition = impulseSource.m_ImpulseDefinition;
impulseDefinition.m_ImpulseDuration = profile.impactTime;
impulseSource.m_DefaultVelocity = profile.defaultVelocity;
impulseDefinition.m_CustomImpulseShape = profile.impulseCurve;
impulseListener.m_ReactionSettings.m_AmplitudeGain = profile.listenerAmplitude;
impulseListener.m_ReactionSettings.m_FrequencyGain = profile.listenerFrequency;
impulseListener.m_ReactionSettings.m_Duration = profile.listenerDuration;
}
}```
Thanks for the help. I will try to implement your ideas.
Either impluseListener, impulseListener.m_ReactionSettings, or profile is null
impulseListener is null
It doesn't matter if it's set here, is it set at the time this code runs
Try logging them to see what's null
then you can try to find out why with actual information
why doesnt it get deleted in editor but in build mode
¯_(ツ)_/¯
also theres no other code affecting it
Presumably because you're doing something in code that removes it in build mode but not in the editor
virtualCamera.m_Lens.OrthographicSize = Mathf.Lerp(virtualCamera.m_Lens.OrthographicSize, targetSize, Time.deltaTime * transitionSpeed);
do you think this could be affecting it
how would this affect it
Have you tried using logs to find out what is null in the first place
It's pointless to try to diagnose a why without a what
its the impulse listener obviously
How "obviously", did you check?
Because I see three things that could be null
Well, I suppose if profile was null it'd error the line before that, but it still could also be m_ReactionSettings
if profile was null it would not go to that 5th kşne
both are used for the first time on the line throwing the error
So, log impulseListener and impulseListener.m_reactionSettings. Do them in two separate logs, so if the first one prints null, you'll still see it before the second one throws an NRE
i did this and it worked
so mreaction settings isnt null
Okay good. That is also sufficient to check which one it is. So, now you know impulseListener is null. You've dragged it in to the inspector of this specific instance of this script, so one of the following two things is happening:
- There exists another copy of this script which does not have
impulseListenerset impulseListenerbecomes null at some point, either because the variable is set to null or the object you were referencingimpulseListenerfrom was destroyed
the camerashakemanager is a singleton
so the impulselistener becomes null
So, either something is setting the variable impulseListener to null, or the object you were referencing impulseListener from was destroyed
Such as when the scene it was in was unloaded
also i made the camerashakemanager not destroy on load
could it be related to that
anyways i think it works fine right now, thank you so much for helping @polar acorn @wintry quarry @shell sorrel
should I add anything here like to create a save or something
using UnityEngine;
using UnityEngine.SceneManagement; // This is needed for SceneManager
public class NewGameButton : MonoBehaviour
{
// This function will be called when the button is clicked
public void StartNewGame()
{
// Replace "StartScene" with the name of your scene
SceneManager.LoadScene("StartScene");
}
}
how would I do that
Im wondering how to like setup a game save system and wondering if I would start the save system in new game or in the actual game
When do you want the save to happen?
- Setting up save data is a big topic I'm not going to try to distill down into a few sentences
- You create a new save where it makes logical sense ... such as when you start a new game
but how would I do that? I dont understand how to create game saves or save data
and playerprefabs confuse me
As I said, I'm not going to try to distill down into a few sentences. I don't have the time to actually explain a whole data structure to someone. You can start by looking up tutorials on how to save data, though if PlayerPrefs confuses you then you have a lot more ahead of you.
It also really depends on what kind of data you're planning on saving.
mainly player position, inventory items, and current objectives
Then no, playerprefs wouldn't be used here. You will have to create your own save data class, and save that using JSON (for example).
Hello. How can I know that enemy and player have no obstacles between them?
Raycast from one to the other and see if it hits anything:
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
And what should be the direction of the ray if I cast it from enemy? Player position?
The direction between the two objects
a position is not a direction
you calculate a direction using target - source
when the guy on learn unity makes a mistake, is it scripted or real
What mistake
hi i recently started coding and now i want to have a small text pop up when you collect an item, everything should work fine in theory but i cannot drag my text from the hierarchy to the inspector and when i try to just select it i get "type mismatch"
Hey so I'm using Unity 2D and I have a funky problem. I have rigid body 2ds and box collider 2ds on my player and game object. Whenever they collide though, the game object and sometimes the player end up off centered and messed up. It's really weird and it's kind of a big problem. I tried including a script to set their rotations to 0,0,0 but that didn't help.
Assuming you're trying to drag the GO from the scene hierarchy to your script component in the inspector, the type of the field on your script needs to be compatible with the type of the component on the game object. What is the type of your field, and what is the component on the GO which you're trying to assign to it?
im confused by a good bit of what u said, down to call and screenshare realquick?
I am not. But you can post screenshots or videos here 👍
You cannot reference a scene object from an asset.
If you're trying to do that -- such as dragging a scene object into a prefab's inspector -- then it will not work.
i have a text-object in my canvas and i try to drag it into the inspector from my other object which should make the text invisible and visible again... idk if that helps
it does not help very much, no
screenshot what you're doing
show us the inspectors of the objects you're using, and show us that they both exist in the scene
Does the type of the object you're trying to drag match the type of the field you're trying to drag it into?
Does the field exist in a scene or in an asset?
so i have to make the text a prefab too?
No, because then it wouldn't exist in the scene
you could have an instance of the prefab in the scene, sure
but you could not reference that specific instance from the enemy prefab
You need to assign this reference when you spawn the enemy.
you simply can't do inspector references from assets.
Why does the Enemy need to reference a Text component though? That seems backwards and inconvenient.
I would reverse the dependency
have the UI thing read data from the Enemy instance in the scene after it's spawned
im really new i just figured it would be the easiest to toggle the visiblity of the text right when i check collision
You can use the singleton pattern too, if there's only one of these UI things.
If you're extremely new then you really ought to use !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
aight guys i think i have an idea of how to fix, ill just try around if anything comes up i'll update and ask again :) thanks everyone
Update: I had to freeze Z rotation under rigid body
There's a little bit of wiggle still but nothing game breaking anymore
hey does anybody know better alternatives for WaitForSeconds? Something that can be in the same function and more easy to read
your question does not make sense
make a timer?
If you're asking about something that can "delay" Update(), you can't
yeah
Not really. You can implement it yourself with deltaTime, but that is LESS easy to read
I don't know what "in the same function" means.
you can only not execute things on certain frames ^^
other than "not in a coroutine"
which brings me to this point: #💻┃code-beginner message
ah, ok
make timer inside coroutine with deltaTime 
how does this compare to a timer in update?
im not trying to make it in update
oh alr
You don't have to run update? easier to control a coroutine
im trying to make the delay in my own funcion
that isnt the one that WaitForSeconds is used for
can you make your function a coroutine?
This makes no sense.
Show exactly what you're trying to accomplish here.
but why?
Subtract Time.deltaTime from a field in Update until it reaches zero, then do something.
I fail to see why you need to avoid coroutines so bad
im just trying to mess around with unity rn
again, this will not let you make the Update method "wait"
if that's what you're trying to achieve
IEnumerator Delay()
{
yield return new WaitForSeconds(1);
var time = 0f;
var timer = 1f;
while(time < timer)
{
time += Time.deltaTime;
yield return null;
}
//Timer done do something?
}```
They're both legible to me :shrug
i know but i was just wondering if there was a different way on doing a wait function
many ways lol
sure: this demonstrates two different ways to make a coroutine wait for one second
It doesn't get much easier to read than yield return new WaitForSeconds(1f);, though
it's pretty obvious what this does: wait for one second
Technically, thread.Sleep will indeed make the Update method wait
true
is this bad practice
lol
yeah I could imagine
so it's great if you don't want your game to work
the ub should automatically refer to the y position right?
it's a poor fit for the "my game shouldn't freeze" crowd
gonna thread.Sleep(Mathf.inf); rq
i don't know what you mean by "automatically"
you are comparing it to transform.position.y
that's very manual
yeah exactly
what type of data does the IEnumerator send back?
so would it understand that i am saying the y position needs to be greater than or equal to a y pos of 45?
or would i need to say somehting...position.y
transform.position.y >= ub will be true (and thus the else-if branch will be taken) if transform.position.y is greater than or equal to ub
wdym it returns IEnumerator
okay cool
All that C# cares about is that you have floats on both sides.
It does not matter where those floats came form
okay thanks
but what is the IEnumerator used for
Unity does some voodoo magic with it to make ti a " coroutine "
there's no magic at all
normally for iteration
oh
hey let me believe in the power of Unity
I just know it works sometimes I don't question it lol
IEnumerator Foo() {
yield return "Hello";
}
When you declare a method that returns IEnumerator and has at least one yield statement, you get an iterator method
but I do know what its doing , I believe you're one who told me about it
An iterator method returns an IEnumerator. This is an object that can give you values one at a time.
Each time you hit a yield, the enumerator stops running and produces a new value.
Unity repeatedly asks the enumerator for values until it runs out.
if i say velocity(0,0,0) would it stop continuing forces from acting on the item (granted no forces are being applied at that time)
That's how coroutines work.
If you yield special kinds of objects, like WaitForSeconds, that changes how often Unity asks for new values
Normally, it asks for one new value per frame.
if you say it after setting a velocity before the fixedupdate loop then sure
might as well just freeze its location though
Therefore, if you do this:
IEnumerator Hello() {
while (true) {
Debug.Log("HI!");
yield return null;
}
}
and start a coroutine with it, it'll log "HI!" once per frame
each time it hits yield, the enumerator pauses
and unity resumes it once per frame, by default
https://gdl.space/liloviqoto.cs
Right now I have an array-based button system, but the problem is that when I want to select the "left" or "right" button it is actually based on the position of the array, not the button relative to world-space. How do I go about doing the latter?
instead of just adding or removing 1 from the index, you need to do a bit more math
although, one thing: if you use UI components with navigation enabled, this will happen automatically
doesn't ui have navigation flow control you can adjust?
you can also manually specify the navigation flow
This should actually be working fine by default. Are you not using Unity UI buttons?
This is what I'm using
so instead of having your code move around with Input.GetKeyDown, you'd just be moving a UI selection around
when you hit Enter with a Selectable selected, it'll receive a submit event
which will cause a Button to fire its onClick event
so actually...just get rid of al of that code and it should work
the only problem is that you need to get an initial selection
you can call Select on the first button when the menu comes up
it wouldnt though right? if gravity is acting on it
just the velocity at that moment
Okay let me tinker with the code and see what I come up with
if you set velocity to 0 and don't change it later then nothing will move
Yup your solution works, however the problem is I don't want an answer pre-selected, how do I avoid that?
I just want the higihlights to come up once the player presses their arrow keys
Then don’t immediately select something
But you’ll need to then select something through code when the player presses an arrow key
note that if you click off of a Selectable, you'll wind up with nothing selected
so this should work whenever there is no selection
instead of setting velocity to 0, how could i prevent a player from getting out of bounds in a more seamless and invisible walled kind of way
right now i just set velocity to zero
you could add force when you're getting close to the bounds
just add an invisible wall
seems pretty simple
and then forcibly stop the player when they get too far
that might be janky
i think i have a solution, but nah i dont want an invisible wall
okay then your choice
nah i think ill do that but make it so it is stronger than the opposing force
it might be bouncy but sure
have fun
yeah like that
I put this in Update but it freezes up the selection, where is a better spot to check for arrow inputs?
private void Update()
{
// Check for arrow input so that we can automatically select an item
if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
answerButton[0].Select();
}
}
hello, whats the best way to store users owned skins? should i create a skin class and make it serilizable, and create a list with that
i have an idea that i should only use forces and velocity since translate seems to be very jittery. is this a good idea or is there a way to counteract that jitteryness (i remember seeing something called smooth something)
You can check if you have a selection right now
EventSystem.current.currentSelectedGameObject
Would highly recommend using the built in UI navigation instead of this
we're switching to that :p
also, if the Automatic navigation misbehaves (it can find the wrong Selectables), you can manually configure it
I do that via script for most of my menus
nvm stupid question
use moveposition for rigidbodies not translate
yes: if you're using a rigidbody, you should tell it to move
instead of changing your Transform and then letting the rigidbody find out about the new position later on
Okay so the arrow keys work perfectly tysm for telling me about the EventSystem. But now my mouse doesn't register the clicks... thoughts?
is that a game for learning japanese? thats sick
Yup, Hiragana (alphabet). Tysm for the compliment
Hey guys, has anyone ever tried to use the flow field pathfinding on a unity terrain using the height of the terrain as the cost field
that'll make everything roll down into a valley!
I've certainly done gradient ascent/descent before for game AI
please don't crosspost
Oops sorry, I'll remove the other one
gradient ascent? 👀
- compute derivative
- move a bit
- 30 GOTO 10
I'm so frustrated because I don't even know where the algorithm fails
I did it with Gaussian functions, which are easy to compute derivatives for
Look at your Event System object while the game is running
It will have some information in the bottom of the inspector
perhaps something is blocking the buttons
(see what your cursor is reported as hovering over)
I used this for an RTS. I added positive influences near resources and negative influences near existing town centers. The resulting point would be where a new town center got built.
Isn't it too computationally expensive
Burst makes it run faster.
I'm actually trying to implement the flow field for an rts too since I thought using A* for every single moving unit would slow down the game a lot
so one problem I'm seeing is that height isn't a vector
you need a direction to move in
I don't use the cost field to calculate the vector field
ah, the cost field is separate
I use it to calculate an integration field which is basically just bfs to calculate the best cost of each cell
Then I try to look for the lowest best cost difference between the current cell and its neighbors that are at the same level
But some cells don't get vectors assigned to them
And some vectors doesn't even make sense lol
Do I need to have something First Selected?
No, this has nothing to do with your mouse problem
Oh
however, you're using the new input system here, and it doesn't provide much information in the Event System for some reason
this is all I get in my editor
Did you used to have working mouse input on the buttons?
Yup, that's how I tested out the system before
Somehow this is overriding it
private void Update()
{
// Check for arrow input so that we can automatically select an item
if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
if (EventSystem.current.currentSelectedGameObject == null)
{
answerButton[0].Select();
}
}
}
did you comment the code out and try it?
https://pastecode.io/s/v953a45p
This is my code if anyone wants to take a look and give me some pointers so i won't become a mad men
You should tell folks what's driving you mad
I can't quite pin point the issue either but my vector field doesn't make sense and some cells don't have any vectors
The cells missing the vectors happened after i added the height check in the flowfield function
I use it to calculate an integration field which is basically just bfs to calculate the best cost of each cell
Then I try to look for the lowest best cost difference between the current cell and its neighbors that are at the same level
But some cells don't get vectors assigned to them
And some vectors doesn't even make sense lol
This is what i do in summary
https://gdl.space/axejoqiwen.cpp
Hmm so I checked to make sure Raycast Target is selected and tried to Debug.Log the Answer Button being clicked but I'm still shooting a blank here.. any ideas?
Show the inspector for a button, as well as the UI hierarchy
Show the inspector for the Correct Response object
I'm wondering if the answer box parent object itself is blocking it
could it be because the button has no sprite assigned for the graphic raycaster to detect?
An empty image can still get hit by a graphic raycaster
Interesting... so my test button doesn't work either
void Start()
{
// TEST BUTTON
TESTBUTTON.onClick.AddListener(OnClickButtonClick);
private void OnClickButtonClick()
{
Debug.Log("Test button clicked!");
}
is it a completely normal button you created from the GameObject menu?
if not, do that
Where did you put that button in the hierarchy?
okay, that should be atop everything else in that canvas
Do you have any other canvases? You can search the hierarchy for them with t:canvas
for this question, how is it that the class begins right above the player variable assignment and no player variables are initialised?
This is not valid code.
exactly
It's missing a player field
Well I got my DialogSystem canvas but that is inactive until speaking to an NPC
it should be like GameObject player; and then they can assign it right?
Right.
yess
Oh shoot maybe it has something to do with the Fader I added...
i don't see how these two things are related at alll
like private Animator anim;
anim = GetComponent<...
GetComponent checks if there's a certain kind of component on a game object
You can always assign to your own fields
(unless they're readonly or something)
what does this mean
idk what a field is
is that a variable
a field is a variable declared as part of a class (more generally, inside of a type)
it's a kind of variable
oh okay
so wym you can always assign to it, you cant assign another script to it if it is private right?
from another object
private is an access modifier.
It determines who is allowed to see that field.
private means that only the owning class can see it.
public means that any class can see it
Shoot it's the Fader I added! lol darn
The fader was overlaid on the screen, blocking mouse input
but what do you mean by it can always be assigned
cause you cant assign another script to a private field right
That is not what private means
The only thing that private means is that other classes can't see that field.
Nothing else.
So if your question is anything other than "does it affect who can see the field?", the answer is "no"
(well, it does also make Unity not serialize the field by default)
so you can use a find method to assign it another object for example right?
a private field
private GameObject foo;
void Awake() {
foo = GameObject.Find("Whatever");
}
What find method are you referring to?
This is completely fine.
private and public have zero effect on any fields defined inside the same class
and they also have zero bearing on the exact kinds of things you can assign into the field
All they do is determine which classes are allowed to see the field.
Simply accessors
Nothing else.
You're probably better off assigning from the inspector though unless absolutely necessary.
Why does Unity default button hierarchy to have the UI text under the button with the image--so frequently it bugs out and the text ends up being rendered underneath the button's image component--which is supposed to be the background of the button
Unity's own documentation dictates that the BUTTON gameobject is rendered on the canvas after the childmost TEXT TMP is rendered
Unity UI is drawn back to front as it goes down the hierarchy. Making the text object a child guarantees it will be drawn in front of the image
This is not true.
You must have something else going on if the text is winding up behind the button image.
note that this is not a code problem, and should go in #📲┃ui-ux
hmmm ok, I'll check settings. Not sure which one would cause that issue
why don't you show us the inspectors for your button and text objects, as well as a screenshot of the scene view showing the problem, in #📲┃ui-ux
How come the editor is angry with me that the faderImage isn't set to active when I'm doing it in my fadeOut function?
public IEnumerator FadeIn()
{
faderImage.gameObject.SetActive(true);
}
public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
{
yield return StartCoroutine(FadeIn());
playerTransform.position = newPosition;
yield return StartCoroutine(FadeOut());
}
you can't start a coroutine on a MonoBehaviour whose game object is deactivated
Crap... so how do I mitigate this fader canvas issue? If I have it active on start it's going to block my mouse
proactively activate it first
If I set it to active at first and then deactivate it in script I still get the same error
void Start()
{
faderImage.color = new Color(0, 0, 0, 0);
// Set Fader to inactive so that it doesn't interfere with other canvases
faderImage.gameObject.SetActive(false);
}
also, what matters is the game object this component is on
since you're just calling StartCoroutine
that's equivalent to this.StartCoroutine(...)
every fixed update, an input packet is added to a list of input packets.
[Serializable]
public struct InputPacket
{
public List<ButtonState> buttonList;
public List<MoveState> moveList;
public bool LTPressed;
public bool RTPressed;
}
LTPressed and RTPressed are both accurately recorded, but the lists dont seem to work as expected
Should I explicity write out this.StartCoroutine?
It's identical to writing StartCoroutine
I'm just pointing out who's running the coroutine
oh
protected virtual void Awake()
{
sendRegister?.Invoke(this);
currentInputPacket = new InputPacket();
}
at the start, a new InputPacket is created.
Where is this code from?
What are ButtonState and MoveState and where are you recording these things? What network framework are you using? Are you sure it supports serializing lists?
im not doing networking stuff yet
i just called it a packet
ok so what isn't working as expected about the lists?
the lists just dont seem to have anything in them.
It's angry at the FadeIn line
public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
{
yield return StartCoroutine(FadeIn());
playerTransform.position = newPosition;
yield return StartCoroutine(FadeOut());
}
did you... put anything in them?
i think its because i didnt initialise them?
yes, im supposed to have.
- You didn't create the lists
- You didn't put anything in them
public void UpPress(InputAction.CallbackContext ctx)
{
if (ctx.performed)
{
currentInputPacket.moveList.Insert(0,MoveState.Up);
}
else
{
currentInputPacket.moveList.Remove(MoveState.Up);
}
}
What is supposed to put anything in them?
is this giving you a NullReferenceException?
What component is this code a part of?
What is that component attached to?
it was yeah, but when i clicked on the object, the NREs stopped happening for some reason
because that forced Unity to serialize it
and unity's serializer abhoirs null
This is a fun surprise
it's attached to all of my building objects
or deal with the possibility of it being null
And are these objects activated?
Remember: what matters is the object your component is attached to
The state of the image's object is irrelevant here.
protected virtual void Awake()
{
sendRegister?.Invoke(this);
currentInputPacket = new InputPacket
{
buttonList = new(),
moveList = new()
};
}
just did this
Honestly I might do this:
[Serializable]
public struct InputPacket
{
private List<ButtonState> buttonList;
public List<MoveState> moveList;
public bool LTPressed;
public bool RTPressed;
public void AddButtonState(ButtonState bs) {
buttonList = buttonList ?? new();
buttonList.Add(bs);
}
}```
that works too
As far as I can tell, yeah the dojo is activated upon game start
Find out by logging it.
Log gameObject.activeInHierarchy right before trying to start the FadeIn coroutine
Interesting... it's false
public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
{
Debug.Log("gameObject.activeInHierarchy : " + gameObject.activeInHierarchy);
yield return StartCoroutine(FadeIn());
playerTransform.position = newPosition;
yield return StartCoroutine(FadeOut());
}
well, there's your problem
That's weird... I'm not deactivating the dojo AFAIK
arent structs value types?
They can still contain reference types.
yes, that doesn't interfere with this.
im trying to record a packet, but the lists are still empty
I'm not sure what that has to do with the previous question
if i've got a list of 1000 packets for example, the movelists and buttonlists are empty. But when I press the buttons, all 1000 update the list simultaneously.
do i need to create a new instance of the list every time
You're probably sending the same ButtonState or MoveState over and over
are lists structs or reference types?
if you want each packet to have a different list, each one needs its own list.
reference
okay i t hink i got it now
This is weird... gameObject.activeInHierarchy is returning false but it's active in the inspector. What the heck is happening?
- You're referencing a different object than you think
- it has a parent that is not active
- it's being deactivated and reactivated within a single frame
It means that this specific instance of the script is disabled at the time the log is printed. It doesn't say anything about any other instances or any other points in time
buttonList = new List<ButtonState>(packet.buttonList); when you do this, does it essentially just duplicate the contents?
it's as if you .Added every element from packet.buttonList into the new List
Oh here we go, I just set the faderImage to active once the coroutine is called and it solved my issue
public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
{
faderImage.gameObject.SetActive(true);
yield return StartCoroutine(FadeIn());
playerTransform.position = newPosition;
yield return StartCoroutine(FadeOut());
}
For some reason it doesn't like to be called from FadeIn
yeah, seems to work as intended now.
@swift crag tried my hand at the hash system again, this time all i did was hash the positions, and again it works for like 36 frames at the start then immediately desyncs lmao
but the replay itself seems to work fine until a bit longer
how would i make my sprite only jump once (Input.GetKeyDown(KeyCode.Space) == true) makes it fly
Likely you're not resetting whatever you're doing in that if-statement.
it resets, if i press nothing it drops back down but if im mid air i dont want the space bar to do anything
you have to provide way more details than that
It doesn't, relative to your code.
GetKeyDown only occurs once
i got this
So you're never resetting velocity