#💻┃code-beginner
1 messages · Page 644 of 1
this is the typical approach:
bool wantsToJump = false;
void Update() {
if (Input.GetKeyDown(...)) {
wantsToJump = true;
}
}
void FixedUpdate() {
if (wantsToJump && isGrounded) {
Jump();
}
wantsToJump = false;
}```
Poll input in regular update and use the value in fixed update
lemme try
it works
it stores the Up imput, but it doesnt multiply the impulse
works for me :D, ty Praetor
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Can anyone recommend some projects to try and make as a complete beginner?
Pong
Thanks
trying to code in a thing so that there can be multiple balls in a breakout game
im trying to clear a list of gameobjects and then re-add all of the gameobjects still in the game
but i keep ending up with an empty element
any ideas why its acting funky
Are you perhaps running this scan immediately after destroying an object? Destroy doesn't run right away - the object still exists for a little while
It might exist long enough to get found by the Find, then gets destroyed
oh
i think i probably am running it immediately
in a diff script i just delete the ball
instead of using FindObjectsWIthTag, just keep a list of your balls and add them as you spawn them/remove them as they get destroyed
you even have an event here ballFell that whoever is maintaining the list can listen to.
is there any way i can fully delete projects from cloud (not just archive them)? I tried going to my repositories to delete them but it's completely empty there.
Archive action mentions that items will eventually be deleted I think.
it just says "This project will be disabled across all Unity Services, and the data, files and information associated with it may become irrecoverable."
So github desktop question, how do you go back to a certain commit, so in this screenshot the highlighted commit, and then continue from there like the first 2 commits didnt exist/ dont matter?
revert those two commits above it
If not pushed you can hard reset backwards, else yea revert them both.
well you could hard reset and force push but for a beginner its not a good idea 🤔
Do i revert one commit, push, then revert the other, push - or can I revert both at the same time, and then push?
In CLI (IDK how to do it in github GUI):
revert way (creates new revert commits):
git revert <hash1> <hash2>```
The "rewrite history way":
```cs
git reset HEAD~2
git checkout .
git clean -df```
either way
doesn't matter
rewriting history is generally frowned upon so that's why I recommended revert first
but if you're alone in the project and especially if you haven't pushed those commits to remote you could rewrite history safely.
They probably did hence needing to force push but if they fuck it up horribly then bye bye data
yeah I would recommend revert as the safest method, and just get over any angst about a "clean commit history" which has little value
so at this point I should be at the highlighted commit basically?
yep!
if you want you can select HEAD and that one and do a diff
it should be clean
I assume github desktop lets you diff two commits through the UI somehow
if not you can always do it on the website
hmm these are the options
Ok the easiest way maybe is to go to view on github
then in the URL you can do like https://github.com/myname/myrepo/compare
then you'll see a UI with two dropdowns
you can paste the commit hashes in those dropdowns
to compare them
you can also do git diff <hash1> <hash2> in the CLI
ideally if we did everything right the diff should be completely empty.
which two are you doing the diff between?
head and the highlighted commit
What's head? Head only means something on your local machine. Are you doing this on the website?
Or you did it locally?
I did it on the newest commit vs the highlighted commit on the website
can you show some screenshots?
let me see
I also tried a test commit to compare against that one as well
weirdly enough these two reverts seemed to reverted me back to a somewhat old build of ours
uhh i might have found the issue? checking this from the visual studio git history
Here's another option that should work. But... what we did should have worked too.
git checkout ac98601 -- .
git commit -am "Reverting directly to ac98601"```
What's in test comm though?
it's just a Demo SDF.asset that changes every time you open Unity
textmeshpro stuff
should be like this right?
Hard to tell until you do the diff again
true. one sec
yep! its empty
yay!
ok sorry about the first attempt
not sure what went wrong there
maybe it was the order of the reverts or something
it was super weird yeah, looks like i'll be learning CLI git when i get the time
I'm sure this can be done in the GUI too, it's just what I know is all
i think the GUI doesn't give this much control, tried fishing everywhere for info on this kinda thing
yeah the GUI is definitely just a bunch of bindings into the CLI, the CLI has everything.
Also different GUIs have different features
funny enough my teacher doesn't know how to use CLI git, so he's always impressed seeing my team member use it in front of him lol
could use this to flex as well
thanks a lot though!!
No problem, happy coding
For some reason Debug.Log returns a false and the effect never begins playing but no missing reference errors are thrown back and to reach the debug.log it would have to start playing it 
likely the particle system hasn't actually started playing at this point yet, it probably won't actually start until the particle system component has updated after calling Play
or there's a startDelay on it
hey I was hoping someone could help me with a rather robust and repeating script. My professor has informed me that using serialization or other methods would simplify this code and make it work far better. The game has 3 hallways and every new hallway is a round. The hallways need to reset at the end of every round. Hence the reason I need to change this code. He also showed me a example where I do not need to repeat every method per hallway. if someone can clarify what I should do that would be great! script is :https://paste.mod.gg/opcroimvrbmj/0
A tool for sharing your source code with the world!
There's no startDelay and the particle system also just never visually starts
are you perhaps invoking the method repeatedly?
because:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/ParticleSystem.Play.html
Note: If you invoke this function again before the particle system has had time to spawn a particle, the particle system restarts its internal counters. This means that if you invoke this function continuously, a particle system with a low emission rate will never start to play.
I just added a check to see if it's already playing and unfortunately it still doesn't work.
nvm I changed it to fixed update and it works now. 
I'm trying to Update my Stamina Bar but I'm getting a Null Reference error.
pm is Null
unless those unsaved changes and its barImage
Fixed it with this Line here.
You should avoid finding gameobjects by name.
using UnityEngine;
public class replacescript : MonoBehaviour
{
public float radius, delay;
public GameObject replaceObj;
void OnCollisionEnter(Collision collision){
explode();
}
void explode(){
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearByObj in colliders) {
Debug.Log(nearByObj.name);
Collider BC = nearByObj.GetComponent<BoxCollider>();
if (BC != null) {
Instantiate(replaceObj, nearByObj.transform.position, nearByObj.transform.rotation);
Destroy(nearByObj);
}
}
Destroy(gameObject);
}
}
huh why all dose working but not destroy the nearByObj?
i want replace building with ruin for explosion
you probably want nearByObj.gameObject
it's not very clear what your question is here
in general whenever you have thing1, thing2 etc that should an array or a list. doing so would let you reuse a single method for spawning, and you wouldn't need separate branches for each hallway number
also your despawning methods are just fully repeated, you don't need to repeat that either
Can anyone help me fix this problem, i cant upload or download any changeset from version control
Try using the external ui client for version control to see what's going on.
The plastic SCM? How can i?
It's explained in the docs:
https://docs.unity.com/ugs/en-us/manual/devops/manual/version-control-desktop-client
i had that downloaded and now its updating it
done but, what now, getting same error
Open the repository with the desktop client
hellooo, anyone knows how i can select a new font i downloaded?, want to use in a text mesh pro
thanks ❤️
public GameObject piececontroller;
private GameObject[] pieces;
public GameObject slotcontroller;
public GameObject slotprefab;
private GameObject[] slots;
// Start is called before the first frame update
void Start()
{
pieces = new GameObject[piececontroller.transform.childCount];s
for (int i = 0; i < pieces.Count(); i++)
{
GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
slot.transform.SetParent(slotcontroller.transform);
slots.Append(slot);
pieces[i].transform.SetParent(slot.transform);
SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
pieceRenderer.sortingOrder = 1;
}
} ```
What should I do for my gameobject[] slot to make it not null (or make it null but no ArgumentNullException.)
You dont give slots a value so its null. Solution is to give it a value: slots = new GameObject[len];
pretty basic stuff. Unity will give serialized fields a value for you but its private so its remains null.
public GameObject piececontroller;
private GameObject[] pieces;
public GameObject slotcontroller;
public GameObject slotprefab;
private GameObject[] slots;
// Start is called before the first frame update
void Start()
{
pieces = new GameObject[piececontroller.transform.childCount];
slots = new GameObject[slotcontroller.transform.childCount];
for (int i = 0; i < pieces.Count(); i++)
{
GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
slot.transform.SetParent(slotcontroller.transform);
slots.Append(slot);
pieces[i].transform.SetParent(slot.transform);
SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
pieceRenderer.sortingOrder = 1;
}
}``` Why it creates boxes in a shape of a sword, I want it to put all sprites in the brown box (slotcontroller).
Why is everything a GameObject? Why not have a script for PieceController and Slot and SlotController?
The number of slot are dependent by number of pieces on the heirarchy, how to fix that.
Are you using a VerticalLayoutGroup Component for your brown box?
You also shouldn't mess with the scale, instead change the width/height of the image (you might need to unlock it first from a parent component thats driving these values)
I use the grid one and not the vertical.
then you probably have to change some of the settings to make it work correctly. Fixed Row Count etc.
hi!
I have a question about meshfilter and mesh
I need to instantiate a mesh on my object but I need to be able to still access the original mesh. I thought that sharedMesh was always the unedited original mesh but when I set .mesh it also sets .sharedMesh it seems!
can I access the original mesh?
and also I don't want to just copy it because it might change (when I resave the source mesh from external for example)
Save the "original" mesh in a variable.
before you change the one on the filter.
How do you suggest I find game objects in code?
Use the singleton pattern, a service locater pattern, opportunistic discovery, tags, or direct serialized references.
Are either of the objects involved prefabs? Or do they both exist in the scene?
They are not Prefabs and they exist within the scene.
if you type "public GameObject myObject;" or such into your script then you can assign a reference to it through the inspector
Then just make the variable public or serialized and drag it in
void InitializeRuntimeMesh()
{
runtimeMeshFilter.mesh = Instantiate(originalMeshFilter.mesh, transform);
runtimeMeshFilter.name = originalMeshFilter.name + "_Deformed";
runtimeMeshFilter.GetComponent<MeshRenderer>().enabled = false;
// Store the original vertex positions and color data.
originalVertices = originalMeshFilter.mesh.vertices;
vertexWeights = originalMeshFilter.mesh.colors;
}
I do this but as soon as I instantiate the original mesh, any changes to the original mash don't carry over any more..
like.. I change some colors on the original mesh in blender, I save it, it doesn't effect anymore as soon as I have this script enabled
in fact, as soon as I call Instantiate(originalMeshFilter.mesh, transform); it doesn't work anymore.. why?
On the first line you did originalMeshFilter.mesh which creates a brand new instance of the mesh
if you want the original mesh it should be sharedMesh
ah yes of course! thank you!
I'm having difficulty attaching the mouse to unity's New input system. with this setup the Camera doesn't rotate.
you need to do look.Enable();. Or protagControls.Enable();
also - you should not be multiplying Time.deltaTime on lines 42-43.
Thank you Praetor!
How do I make fields visible in the inspector but have them greyed out like this? I'm assuming it's an attribute on the field itself, but I looked on the unity docs and couldn't find anything
you'd have to write a custom editor or property drawer
or use a plugin
like NaughyAttributes
Ah OK. Ty for the quick response 
I have in my prefab, some fruits like banana and apple, and so one... that can increase health of my player. In scene I have multiple instance of them so like apple (1), banana (2), apple (3). I want to create a script that will increase player health based on fruits, by 1 for banana, 3 for apple. In the script how can I know if the gameObject is apple or banana?
I already tried gameObject.name but it return apple (3) if it is the third instance.
I only want to get apple for the condition
yes you should create an Enum, or SOs. Using strings isn't very flexible , you would have to look for specific keywords but its prone to errors.
eg
if(gameObject.name.Contains("apple")) etc.. it would not be flexible
Add a script to the fruit objects that tells what they are
or even better, tells how much the health increase is
public class FruitItem : MonoBehaviour{
public int HealthIncreaseAmount = 1;
}```
Can you give more exemple on the Enum?
enum will work but actually thinking about its not going to be very flexible as just passing a value, unless you plan on doing other things
public enum FruitType { Apple, Banana, Orange }
then you would need a variable in the Fruit script to what it is..
public FruitType Fruit = FruitType.Apple; // a default value
but yeah do it like Nitku suggested, something like this
#💻┃code-beginner message
Ok I'll try it, thank you guys
Hello! I am trying to create a random maze generator, I already have the script and prefabs for the walls but how can i bake the navMesh surface for the floor whenever it generates randomly? if it is possible?
"why is my pineapple not working"
Hey! wondering if I could get some help fixing my A*Pathfinder script. For some reason, I keep getting some weird errors in paths where the entity goes backwards?
no 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 sry
A tool for sharing your source code with the world!
thanks @rich adder
as you can see, it sometimes goes in a straight line, and others will go a step back then forward
oh this is not the A* project ? this is custom ?
haven't done own a* algo in a bit so I probably cannot help much.
I would probably first start with visuals. Start with drawing gizmos on the projected path , I'm guessing there is something there being added from your previous thats not suppoed to be there
Yeah I just thought it was a bit too overwhelming and figured Id try myself
Something i should note is that it worked fine before adding diagonal movement
But I’ll try debugging it with gizmos
if (moveDictionary.TryGetValue(evt.newValue, out Move move))
{
will this out function return a copy of the Move object, or the reference to the move object?
reference types is always the same object
you're just carrying over an address to that obj
here just puts the result in a local variable but its the same object
awesome, was pretty certain of this but just wanted to make sure just in case. thanks 😄
how to name a field differently in inspector?
example:
[SerializeField] private TextMeshProUGUI attackTMP;
I want it to show as "Foo" in inspector while remaining as attackTMP in code.
is that possible?
custom inspector could probably do that
ohh, there is no built-in attribute such as
[SerializeField][Alias("Foo")] private TextMeshProUGUI attackTMP;
or something of the sort?
That's unfortunate, thanks for the tip
naughty attributes has something that does this
Do remember you can also use [FormallySerializedAs] to safely rename a serialized field
Thanks ❤️
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
I dont think this is a coding issue, but i find it strange that it displays this path after i moved most of my stuf out of the OneDrive folder. This should be C:/Documents
the folders permissions are already screwed up if it was in OneDrive
if you want your project to not implode STOP USING ONEDRIVE WITH IT
gdrive and dropbox are also a no go
how do i change the light source to color, im not seeing it in the environment settings in the lighting window, im using hdrp
Yeah i hate how OneDrive turns on automatically
if I want the camera to store an enum keeping track of which room it's in, and I want the managers for every room to keep track of what that value is, should I add the camera to every roomManager script, or is there a way I can make the cameraManager script accessible from all my other scripts?
like
public cameraManager cameraManager;
in every roomManager is my current plan, setting it in the inspector
Use the singleton pattern, or use static events.
Or just register the camera with the room when it enters that room, for example
it's hard to say for sure without understanding how this system works in your game
currently trying to plan out how it's going to work, so I don't make it stupidly and have to patch it later
Goal is to have six 2d rooms in a 2x3 array, and using the WASD keys pans the camera between them, and rooms like Comms only activate their systems and controls when currentRoom = Comms
Camera has the cameraManager script that holds the locations of the camera anchors and controls the wooshy motion between them and stores currentLocation
sounds like you should have a centralized RoomManager that's a singleton and it can just activate each room as it switches to it (and deactivate the previous room)
it can control the camera too
or the camera could listen to an event on the ROomManager
all the individual compoonents could also just listen to an event on the RoomManager
like an OnRoomChanged event
which could have arguments for the previous room and the new room
for this part I would recommend using cinemachine
have a virtual camera in each room and you can just switch between them.
can I switch between them with an animation and some 2d parralax effects, or will it just snap the camera as it switches from one to another?
you can fully control the transitions in cinemachine
the default is a smooth blend
thanks for the info I'll start reading up on how to use that
so for the first part, you're reccomending making a roomManager that holds each room's individual managers in itself, and toggles them on and off when needed?
yes - an array or list of Rooms, something like that
I can tough it out and deal with it if need be, just at a later date, but;
Can anyone reccomend a good text tutorial for using cinemachine? I don't ususally learn very well with video tutorials compared to being able to read it. Plus I don't have headphones for audio for another day
These should help https://learn.unity.com/search?k=["q%3Acinemachine"]
just skip the video bits
foreach(Fade audio in AudioFadeOuts){
audio.source.volume -= audio.time * Time.deltaTime;
if(audio.source.volume <= 0)
AudioFadeOuts.Remove(audio);
}```
is this a safe way of removing audiosources from a list?
Fade is a struct with an AudioSource (source) and a float (time)
the idea is that I want to make it so some sounds fade out instead of abruptly cutting out
idk if theres a better way for it
I keep getting this, but I'm not sure if its a problem
I'm pretty sure that it is a problem because you'll never execute that code without getting an exception.
You cannot remove an item from a collection while enumerating over it . . .
You can't modify a list / any collection that you're for-eaching through
I mean, I figured
You must use a reverse for loop . . .
ah okay
thanks!
I'm trying something like this
if (AudioFadeOuts.Count > 0)
{
for (int i = AudioFadeOuts.Count - 1; i >= 0; i++)
{
Fade audio = AudioFadeOuts[i];
audio.source.volume -= audio.time * Time.deltaTime;
if (audio.source.volume <= audio.maxValue)
AudioFadeOuts.Remove(audio);
}
}```
but I keep getting out of range exceptions
even though it shouldnt be possible for it to be out of range like this
look at this line again: for (int i = AudioFadeOuts.Count - 1; i >= 0; i++) . . .
shouldnt it be less than or equal?
read what you set the loop to do . . .
because I want to be able to access -
oh
fuck
right
my bad, thank you!
shit
remember, you reversed it . . .
hello! i'm a newbie in gamedev.
so i have made a dialogue system following this tutorial from youtube: https://www.youtube.com/watch?v=DOP_G5bsySA&t=23s
this dialogue system has a button which if u press, will continue to the next dialogue. it also has an animation that "types out" the dialogue.
now i want to use it in a cutscene--which i am animating using a timeline. in this cutscene, characters are moving around and talking to each other. talk first, then move.
i cant seem to find a tutorial on how i can do this. is there any way i can do this? thank you!
Ive done this before, you can make your own playable track and playable to setup this behaviour
Does Unity have a feature to serialize a dictionary?
Making it public doesn't seem to show up in inspector
Not by default no
There is a blog post about it but its a tad old but most things should still apply I think. You will have to pause the playable director when you show your stuff if you want it to wait (but then animations playing pause too).
https://unity.com/blog/engine-platform/extending-timeline-practical-guide
You can check the asset store for free serialized dictionaries if you don't want to bother implementing your own or pay Odin etc
What is the best method to grow or shrink a character. methods I have tried have not worked with collision detection and have forced the character into the ground or only worked while in the air
What doesn't work with collision detection exactly?
its probably just too deep in it's life to ever budge from not having it but you are def. right imo
So when you tried to grow it I think it would grow into the floor or the ceiling so it wouldn’t do it.
I think you need a spherecast or something to check whetever any objects are on the way
There's a lot of ways to do this
How does unity decide what point to scale from is it the centre of the game object or one of the corners
I think it's always the center
You could parent the growing object to an empty gameobject with a position offset if you want a different pivot
And scale the parent instead of the original object
I've used this method quite a bit but somehow it feels a bit hacky, don't think there's any better way though
In Blender you just set the pivot and done
Got it working thanks
Chat this is probably a really stupid question and i'm probably just an idiot in general but HOW DO I MAKE MOVEMENT RELATIVE TO CAMERA ROTATION
Cause i'm trying to make a first person thingy and if i rotate my camera around and press W, it still moves in the "global" forward direction? Idk if i'm explaining myself well
Lemme quickly send over my code
On the "Player" object:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] InputAction jump;
[SerializeField] InputAction movement;
[SerializeField] Rigidbody rb;
[SerializeField] Transform cameraTransform;
[SerializeField] float jumpForce;
[SerializeField] float moveSpeed;
private void Start()
{
jump.Enable();
movement.Enable();
rb = GetComponent<Rigidbody>();
}
private void Update()
{
ProcessJump();
ProcessMovement();
ProcessSprinting();
ProcessBodyRotation();
}
private void ProcessJump()
{
float jumpingValue = jump.ReadValue<float>();
if (jumpingValue == 1f)
{
doJump();
}
}
private void doJump()
{
rb.AddRelativeForce(Vector3.up * Time.fixedDeltaTime * jumpForce, ForceMode.Impulse);
jump.Disable();
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Floor")
{
jump.Enable();
}
}
private void ProcessMovement()
{
Vector2 movementValue = movement.ReadValue<Vector2>();
rb.linearVelocity = new Vector3(movementValue.x * moveSpeed, rb.linearVelocity.y, movementValue.y * moveSpeed);
}
private void ProcessSprinting()
{
if (Keyboard.current.leftShiftKey.IsPressed())
{
moveSpeed = 10;
}
else
{
moveSpeed = 5;
}
}
private void ProcessBodyRotation()
{
transform.localRotation = Quaternion.Euler(0f, cameraTransform.rotation.x, 0f);
}
}
Wow mighty text wall sorry
hello, i trying to work in a chess game but that really complicated can someone have some tips for making it ?
Guys i have created this script for enemy which can follow my player and shoot but it just goes on following my player everywhere in map i want to set the minimum range so that my enemy only starts following my player when in that range can anyone tell me how to do it please... Here is my script
look into using the camera's transform
something like this if you're moving on the x,z plane:
Vector3 moveVector = transform.forward * inputMoveDir.z + transform.right * inputMoveDir.x;
transform.position += moveVector * moveSpeed * Time.deltaTime;
is the "transform.forward" meant to be the camera's transform?
yeah
my math may be shaky but try it out and see if it works
Basically we use get the camera's forward and multiply that with the scalar value of the forward movement (if negative, this would be back instead of forward).
Likewise for the right movement (which would be left if value is negative).
Left and back are not needed since the scalar would be negative if it is the opposite direction.
Now we use that vector as our direction instead of out global XYZ (default vector3)
yeah it is somewhat "weird" to get haha, I totally get you
Quick question for monobehavior singletons, is there a way to always have it added or will I need to spawn the GO in the menu and testing screen if it doesn't exist?
you could have your singletons in a separate scene and have that loaded additively
ah so have a Constants scene that gets added to every scene when and if needed?
well, loaded in addition to other scenes, not added to other scenes
ah gotcha! thanks
private GameObject[] pieces;
public GameObject slotcontroller;
public GameObject slotprefab;
private GameObject[] slots;
// Start is called before the first frame update
void Start()
{
pieces = new GameObject[piececontroller.transform.childCount];
for (int i = 0; i < piececontroller.transform.childCount; i++)
{
pieces[i] = piececontroller.transform.GetChild(i).gameObject;
}
slots = new GameObject[pieces.Length];
for (int i = 0; i < pieces.Length; i++)
{
GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position, Quaternion.identity);
slot.transform.SetParent(slotcontroller.transform);
slots.Append(slot);
* pieces[i].transform.SetParent(slots[i].transform);
pieces[i].transform.position = slots[i].transform.position;
SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
pieceRenderer.sortingOrder = 1;
}
}``` I got a nullreferenceexception at the line where i put the * in.
find out what's null and make it not null.
It's either
pieces[i] or slots[i]
Null reference exception is object is not set to an instance of an object.
Double click that error and see which line it takes you to
It takes me to the line where i mark *.
Ah sorry I missed that part
Why are you using Append here?
Do slots[i] = slot; instead
I don't have that much knowledge of unity coding so sorry.
Append returns a new sequence with the new item at the end of it, so that does nothing here
I know what a null reference is.
The element i in either of those two arrays may be null.
I got the answer already, it's slots[i] is null.
https://pastebin.com/n5nTy2Qy My code for finding hexagon grid adjacent tiles lol, kind of just winged it.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Didn't realize there was quite a few of edge cases
Works though 👍
how do you stop playerprefabs from falling through floor
collisions
Hello I am trying to make the border to my map but the colliders are too large and take up portions of the map. Is there a way to make them smaller? I've tried several things but i'm lost
You can edit the physics shapes for your sprites in the sprite editor
Hello this maybe a dumb question but is there anyway I can detect collisionExit for character controllers? (Also trying to use OnTriggerEnter but its not working send help plej)
I see thank you!
nvm just had to make it more thicc
Is there an event for touchscreens similar to
Mouse.current.leftButton.wasPressedThisFrame
Can't find one
Oh wait, it's Touchscreen.current.press.wasPressedThisFrame
I was missing that "press" in the middle
Some stuff needs enhanced touch enabled (the docs seem to be quite wrong for the old input -> new input for touch examples)
i discovered this all the hard way 😦
What's the general logic over whether to have moving objects and parts moved using physics and velocities and when to use animations?
And when to use animations created in an animation program, vs when to use unity's animation system?
I'm trying to make a clicky clacky satisfying 25 pounder gun loading system in unity 2D, and I'm trying to decide how to implement it
I want the player to use the mouse to click and drag the moving parts to operate the various controls
My current plan is to have the control part give an output in the form of a percent, and have it control movement of the affected parts by an equivalent percent, but I'm not sure if that's optimal or easiest to code
In my current system, I can pretty easily do linear multiplicative actions, where a large motion is multiplied by a fraction to make a smaller motion, and I think I can also make it do a logarithmic progressing with accelerating progress but it's convoluted to the point I wanted a sanity check
Hello
Is there a way to put a parameter when we assign a method to an action ?
Because, I use the repetitive method to assign the context value of my button for my input system of my game.
My script : https://pastecode.io/s/cjdahyry
I really don't recommend this approach
You're introducing a middleman for no benefit
and having to write all this boilerplate code.
I recommend deleting 90% of the code in this file. It should just be like this:
https://pastecode.io/s/rt6mi97r
Then for example if another script wants to handle jumping it can just check this in Update:
InputManager.Instance.Input.JumpInput.WasPressedThisFrame()```
or it can subscribe to an event itself
InputManager.Instance.Input.JumpInput.performed += OnJump;```
By trying to centralize all of the input handling and putting it in variables, you have to know ahead of time and in one file how every single input value is planned to be consumed by other scripts, and any time you change something you need to change it in multiple places
if you just let the scripts handle things themselves you cut your work in half
The only thing this centralized manager should really do is manage the single instance of the generated C# class.
Currently doing Unity’s course… Is it worth it?
Best to ask this in #💻┃unity-talk, but it really depends on your learning style, if you learn by following it, it would be good to do so, if you don't learn from it or think you can learn a better way, try that better way/find a way you can learn.
thx
ok so I have a very strange and probably basic question. I currently have mouse movement set up using vector and transform localEulers, the camera it works great with no stutter, when I move it to the parent the rotation breaks the rigidbody inerpolation, I want the left right mouse to rotate the character left and right and up down just to rotate the child camera, would I need to add a torque to the player body if so how would that be calculated
rotate via the Rigidbody not the Transform
in most cases you can just set rb.rotation in place of where you would be setting transform.rotation
public void HandleBallCollision(Collider2D collision) {
// Check if the collided object belongs to the ball layer
if (collision.gameObject.layer == _ballLayerIndex) {
// Ensure that the game logic is properly initialized before updating the score
if (_gameLogic != null) {
// Increment the score of the player based on the collision event
_gameLogic.AddScore(1, _playerType);
Debug.Log("Score added to " + _playerType.ToString());
}
else {
// Log an error if the game logic reference is missing
Debug.LogError($"Game logic is null in BallCollisionHandler for {_playerType}.");
}
}
}```
For such a long time the condition ``collision.gameObject.layer == _ballLayerIndex`` keeps checking false even tho the objects clearly collide (one goes trough the other, how can I fix this
What calls HandleBallCollision
public abstract class BaseBallScannerScript : MonoBehaviour {
// Reference to the BallCollisionHandler for managing ball collisions
private BallCollisionHandler _ballCollisionHandler;
// Abstract method to retrieve the player type (e.g., left or right)
protected abstract PlayerType GetPlayerType();
// Unity's Start method for initialization
void Start() {
// Initialize the ball collision handler with the player's type
BallCollisionHandler.SetBallLayerIndex(3);
_ballCollisionHandler = new BallCollisionHandler(GetPlayerType());
}
// Unity's OnTriggerEnter2D method for detecting ball collisions
void OnTriggerEnter2D(Collider2D collision) {
// Pass the collision event to the BallCollisionHandler
_ballCollisionHandler.HandleBallCollision(collision);
}
}
here
Okay, so then it'd seem that this object never has a trigger interaction with an object whose layer is equal to _ballLayerIndex
yes
Are you getting either of the logs in HandleBallCollision?
Then at no point is an object with a script that implements BaseBallScannerScript ever have a trigger interaction with an object whose layer is equal to _ballLayerIndex
Consider putting in some debug logs to find out at which point something you aren't expecting is happening
what do you mean by trigger interaction?
When an object with a rigidbody moves into a position causing one of its colliders to overlap with a trigger collider
oh I see so it means they don't really have to collide with each other
like not passing trough each other
A trigger is specifically a collider that doesn't cause a collision
It's not solid, things pass through it. It detects if it overlaps a collider instead
oh ok
thanks
last time when I made flappy bird the condition condition was true and it was rather a box collider 2D here I used edge collider idk it's related or no
Before trying to guess at solutions, you should find out what the problem is. Check if the function is being called at all, and if it is, check the object's layer and what _ballLayerIndex is set to
Collider[] results;
public float checkRadius;
private void CheckGround()
{
int hitCount = Physics.OverlapSphereNonAlloc(transform.position, checkRadius, results);
isGrounded = hitCount > 0;
}
Why would this not work?
What doesn't worrk about it
even if i increase the checkRadius it still says its not grounded
What calls CheckGround
the transfrom is at the feet
in update
it used to work when i was doing a single raycast down
Where do you create results? What size is the array?
i dont create it, do i have to? cause like if i were to create it every frame wouldnt that impact perfromance or GC?
You don't create it every frame
But you need to create it somewhere
that's the point of using NonAlloc
it reuses an array
so i can just do this?
Collider[] results = new Collider[1];
or does it have to be bigger
If the length of the buffer is 0, then it will never return anythign greater than 0
oh so 1 is enough right?
How many objects do you want to detect in any given sphere check?
bigger than 0
sorry if i didnt understand the question 😭
but yeah if there is more than 1 detection it means its on ground
Okay, but how many objects do you want to check
If you just want to see if anything is in the area, and don't care what it is, why not use CheckSphere
wouldnt that allocate?
oh yeah thats true
Can someone look into this please
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
I have added the horizontal movement axis to my camera movement and it has a nice smooth rotation whenever you go from a standstill however going from one directon to the other is instand and jarring?
"""cam.localEulerAngles = Vector3.Lerp(cam.localEulerAngles, new Vector3(camRotate.x,0,Input.GetAxis("Horizontal")*-5), camSpeed);"""
should I just have a seperate value and use movetowards or is there some other issue
lerping euler angles is a recipe for sadness usually
Lerp doesn't account for the "wraparound" effect that angles have
if (player is in range)
{
follow player
}
something like that. it seems you have the necessary methods already for following and detecting when player is in range
also transform.localEulerAngles is liable to suddenly switch from one equivalent representation to another (there are infinite equivalent euler angle representations)
You're better off using Quaternions here and RotateTowards or Slerp
ok i will give it a shot
But what should i refer to when i say follow player should i first use Public Transform player and then call it?
Because if i just tell him to follow player it won't understand? should i do like that or...?
you already have a variable called Player0 it seems? if you assigned the player's transform into it in the inspector then it should work
ya
he was talking to someone else
But will unity understand what to do when i just say follow??
or need i also need to define it?
no i just gave an example what it should roughly look like, following is done with Vector3.MoveTowards
or Vector2.MoveTowards
you've used it in your script already
ok so basically i should first define follow with transform position and then use it there am i right??
ya but i need to define it for follow function if i want to use it seperatly
wait i just realized isnt this already doing what you asked?
if ( Vector2.Distance(transform.position, Player0.position) > range )
{
transform.position = Vector2.MoveTowards(transform.position, Player0.position, speed * Time.deltaTime);
}
i tried but no it is not
i tried lowering the range and also increasing but no it dont work
I thought the same at start that there was no mistake but i am not getting what to do exactly
i think you gotta reverse the >
nice idea i will see
will let u know in few minutes if it works
Bro thanks soo much it totally worked only a little siffrent issue whihc i hope i can fix thanks again
public enum RoomLocation
{
Menu,
Comms, Gunnery, Barracks,
Strategy, Loading, Storage
}
private class roomConnections
{
public RoomLocation up;
public RoomLocation down;
public RoomLocation left;
public RoomLocation right;
}
private roomConnections Menu;
private roomConnections Comms;
private roomConnections Gunnery;
void Start()
{
//initialize
Menu.down = Comms;
}```
I'm trying to store the rooms located to the up/down/etc of rooms, and it's not letting me assign the values, I get an error with attempting to assign Menu.down, a RoomLocation variable, to be Comms
Wait I just realized my error I am a fool I used the same names twice
Yeah... This is very confusing naming and also doesn't make sense
Yes, your variable names are the same as the enum names . . .
But it would be like Menu = roomConnections.down; for example
That would compile
No idea if it makes sense in your concept here though
Everything seems confused here
I also missed the part of the code block that included public RoomLocation cameraLocation, importantly, I may just need a break before my brain completely turns to soup
Sorry for confusion I think I got it
I would also recommend trying to conform to C# naming conventions
It should make things a little easier to think about
I should probably print something to pin over my monitor to remember that
For example a class name should start with a Capital letter
if I have public CinemachineCamera[] cameras; is there a way I can refer to a camera as "comms" instead of as cameras[0] in the script? I could just put camera Comms = cameras[0] in Start() but that seems suboptimal
Putting that in start would assign the variable to what cameras[0] is at that moment. If the list changes or you assign a new thing to cameras[0] it wouldn't update Comms
Yeah, that's part of why I thought that solution seemed suboptimal.
I need seven cameras, one per room plus one for the menu, that that won't chance, so it'll be a static list
Probably just use cameras[0]
hey someone on to help me ?
#💻┃unity-talk message
and don't crosspost
sorry i first thought my question would be best in scripting, then i sent in unity talk
Just make a getter property or method
Method:
CinemachineCamera GetComms() => cameras[0];
Property:
CinemachineCamera Comms => cameras[0];
That way you are doing the same thing but are wrapping it with something more readable
Hi people, if you can help me with an error I have in this, the code does not show any error but if I press the space key it does not do the animation and also does not jump the collider is set with ontriggerenter and exit what is the animation of idle and walk if it works well but the jump does not
Here is also a photo of the animator
!code
also make sure the conditions are actually what you expect them to be, use logs if you have to
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
using System.Collections.Generic;
using UnityEngine;
public class SirenHead : MonoBehaviour
{
public float velocidad = 10f;
public float rotar = 10f;
public Rigidbody gravedad;
private bool caminando;
public Animator animator;
private bool ensuelo = false;
public float saltarfuerza = 5f;
void Start()
{
gravedad = GetComponent<Rigidbody>();
}
void Update()
{
float moverx = Input.GetAxis("Horizontal");
float movery = Input.GetAxis("Vertical");
Vector3 moverse = new Vector3(moverx, 0f, movery);
transform.Translate(moverse * velocidad * Time.deltaTime);
float RotarX = Input.GetAxis("Mouse X")*rotar*Time.deltaTime;
transform.Rotate(0f, RotarX, 0f);
bool estacaminando = moverse.magnitude > 0.1f;
animator.SetBool("run", estacaminando);
if (ensuelo && Input.GetKeyDown(KeyCode.Space))
{
gravedad.AddForce(Vector3.up * saltarfuerza, ForceMode.Impulse);
animator.SetTrigger("saltar");
ensuelo = false;
}
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("suelo"))
{
ensuelo = true;
}
}
private void OnTriggerExit(Collider other)
{
if(other.CompareTag("suelo"))
{
ensuelo = false;
}
}
}
a powerful website for storing and sharing text and code snippets. completely free and open source.
okay and have you added any logs yet?
no
well then do that. also when sharing code, please either use a bin site that will actually automatically add syntax highlighting or have the courtesy of selecting the correct language so that it is added. big gray blobs of text are ass to read
im trying to make a game where hitting a plane with a bullet makes the bullet split off into shrapnel. further hits by the shrapnel also create more shrapnel. my code works when the bullet hits a plane, but when a shrapnel hits a plane the next shrapnel has no force. also debug.log doesnt work in the secondary shrapnel and idk why. heres my code: https://paste.mod.gg/qeikmzkxikgj/1
would really appreciate any help been trying to solve this for a while
A tool for sharing your source code with the world!
If the log does not appear then the object is not active in the scene. Start is automagically called when a script is enabled . . .
It should run as soon as the shrapnel is created . . .
start will be a frame later, no?
and you don't receive the, "Force applied . . ." debug at all?
If that's the case, then the Rigidbody component should be null as well. Check if the rb field is null or assigned . . .
Oh, it's private; add [SerializeField] in front of private Rigidbody rb; to see it from the inspector . . .
What doesn't come up?
the check box thing
No, you should see the variable rb appear in the inspector under the script . . .
Now play and check if the secondary shrapnel has their Rigidbody component assigned . . .
This happens during gameplay?
yea
Then the log will appear. They both happen within the same method . . .
why are the components disabled?
i checked it only increases for the first shrapnel
I was just going to ask why the components are disabled as well . . .
Because if the component is assigned, then the log will appear. It just doesn't make sense otherwise . . .
are you doing something silly like cloning a scene object rather than a prefab?
Are you cloning . . . damn, box is on it . . .
my code is here
i think im just instantiating another prefab
pretty sure
You need to check. This doesn't tell us if they are or not . . .
Can you show us the console logs (after the shrapnel splits)?
Place this log at the top of Start . . .
Debug.Log($"Start called on <color=yellow>{name}</color>");
How many pieces of shrapnel did you have?
0 (clone) and 4 (clone)(clone)
(clone)(clone) means you're cloning something in the scene
You're instantiating the wrong object then . . .
Look at the log. The name of all the instantiated clones are Shrapnel(Clone) . . .
But you said you have 0 of those and 4 (Clone)(Clone) GameObjects . . .
is the ShrapnelScript component attached to the Shrapnel prefab?
yes
so that would be why. when it is instantiated the shrapnelPrefab variable gets updated to point to itself because all references to its own prefab get updated on instantiation
Did the log appear for the correct number of shrapnel?
so when the first instantiated prefab goes to instantiate another it ends up just cloning its self
it was 2 1 1
does anyone know how do you make a linerenderer stay on top of an image or canvas?
so do i have to create another object or is there another way i can do it
something instantiates the object at runtime so have that object just pass the prefab to the instantiated objects so it isn't just a chain of them cloning themselves
or instead of having shrapnel instantiate shrapnel, have something else instantiate the shrapnel
nvm
ok i see thank you
so the prefab is referencing the shrapnel that was already made so instantiating it just makes more copies of that object?
no the prefab references itself, so when it is instantiated that variable is updated to reference itself (the newly instantiated object)
it works now thank you
wait since i am making 2 shrapnel each collision, each shrapnel should get a different prefab passed down to it right?
they just need to have the actual prefab passed to them if they are instantiating the prefab as well. it doesn't have to be different ones, it just has to be the actual prefab asset
#1180170818983051344 to show off your work. this is not an advertising channel.
Can't convert a double to float?
for(var i = 0;i < RadialCount;i++){
BasicBullet p = Instantiate(projectile, transform.position, transform.rotation);
p.transform.Rotate(0.0f,0.0,(float)360/RadialCount);
}
Everything else is working but I don't know how to make the 360/RadialCount float if that doesn't work.
Wait nvm it's argument 2 I forgot to put f after the literal
Should I delete a question if it's no longer necessary to avoid cluttering the chat
make sure that your !IDE is configured so that it underlines errors in red so you can spot them more easily 👇
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
• :question: Other/None
Wait I've done all that
Is this the problem
I installed it though
With the popup
restart pc
@tacit torrent Hey, it's better to use Visual Studio 2017 to 2019, that one works very well, especially on a laptop with a Pentium Dual Core T4500 and 4 GB of RAM.
Probably would work better... But then I would have Visual Studio and VS Code
But to avoid complications, use the 2017 or 2019
The vs code does work but it's not the same, really.
well of course it's not the same lol
personally i find vscode to be plenty, so if you're already used to it, may as well just use that
in lua i can define WHO to collision enter, how do i do it in unity then?
local obj = workspace.obj
obj.Touched:Connect(function()
print("touched")
end)
void OnCollisionEnter(Collision collision)
{
//??? how do i even define which obj to collision detect
}
you can use an if statement and things like CompareTag, GetComponent, etc to check what you collided with
but when i use this function which object will detect? script parent?
what do you mean?
like this function uhhh its just a collision detecting i dont see which object is doing it
wdym by "which object is doing it"? this is a unity message, it will be called by the engine when this object collides with another (and the other requirements, such as collider and rigidbody existing are met)
this.gameObject refers to this objects own gameobject, not its parent gameobject
i think you may be misusing the word "parent" there
maybe
Whenever the enemy moves, it vibrates. Does anyone know why? https://paste.mod.gg/onzutikssqgs/0
A tool for sharing your source code with the world!
i would say something to do with the rigidbody on the enemy
It has instructions though, did you try following them?
yup
placed unity folder into my project folder
fixed
Was wondering if this is bad practice or not, I'm talking about the break condition of +1000 loops
This is a band-aid fix of the game crashing if the pathfinding is unable to find a suitable path (gets stuck in the while loop)
Show the rest of the script for better context? Mainly LoopAdjacents()
There's likely a better way to avoid that
Oh no it's probably bad XD. My first attempt at pathfinding.
I mean if it gets stuck at the first iteration then it will do 999 iterations for nothing
private int LoopAdjacents()
{
int lowestFcast = 999;
GameHex nextHex = gm.gameGrid.gameHexes[current];
foreach (GameHex hex in gm.gameGrid.gameHexes[current].adjacentHexes)
{
if (hex.isObscured || hex.evaluated)
{
continue;
}
hex.hCast = (int)Vector3Int.Distance(target, hex.gridPosition);
hex.gCast = (int)Vector3Int.Distance(current, hex.gridPosition);
hex.fCast = hex.hCast + hex.gCast;
hex.evaluated = true;
if (hex.fCast < lowestFcast)
{
lowestFcast = hex.fCast;
nextHex = hex;
}
}
Vector3Int nextHexPos = nextHex.gridPosition;
Debug.Log(lowestFcast);
path.Add(nextHexPos);
gm.gameGrid.gameHexes[nextHexPos].GetComponent<SpriteRenderer>().color = Color.green;
current = nextHexPos;
return lowestFcast;
}
From a quick look, you should probably do something like cs private bool LoopAdjacents(out float lowestFcost)
instead
!code
Return true only if anything was found
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
So like ```cs
bool foundAny = false;
...
if (hex.fCast < lowestFcast)
{
foundAny = true
lowestFcast = hex.fCast;
nextHex = hex;
}
...
return foundAny;```
When it returns false, break the while loop
https://paste.mod.gg/qfwicezbtatl/0
this is my wallrunning script.. for some reason, when i walljump (adding force to up and normal direction), the force to the normal of wall is not added properly... the u force works alright but the normal force is not added. it rubber bands me back to the wall. i've been stuck for a week, any help would be appreciated
A tool for sharing your source code with the world!
Oh right, that's a better solution thanks
if you're trying to find the shortest path you should probably use bfs
but im not seeing what the loop actually does tbh
It doesn't even quite work yet :D, in this case the selected tile is the target, but it can't find the path to it around the red obstacles because it can't backtrack
have you tried to implement more classical pathfinding algorithms?
like bfs i mentioned before, aka floodfill
Ye I should, I just recently had a CS class about them
Hello, I wanted to create an inventory system for my game. I already have a sword object in my game that I can hit with a mouse click. I haven't found a video yet where my sword is active in the slot and I can actually use it, and if I haven't selected anything, it just shows my hand. Can someone help me? This is a very important matter.
I was wondering how I could clamp the X rotation for Cam_Leaning. Would I get cinemachine range via script? how would I do it? https://paste.ofcode.org/3bbQL7wWvExTtEiEBUgSLic
We might need more details. Do you have a prototype that isn’t working or are you lost on how to start? Some photos would help
Yeah i think im very lost at the moment and I think some tutorials are just to complicated or dont have the same as i Do
Inside of the Player (The Child) is my Sword object
I want to make the inventory so open that I can add a shop where items are added to the inventory. In most tutorials, there's a runner where the items are laying on the ground and you just pick them up, but unfortunately, that's not what I want.
you're in a code channel, where is the code ? which part isn't working etc.
oh ok if i have a problem i can send it
If in those videos, where runner can pick them up. Just see how they do it with which method. And you can use that any way you want.
always check the docs
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/api/Unity.Cinemachine.CinemachinePanTilt.html#Unity_Cinemachine_CinemachinePanTilt_TiltAxis
https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/api/Unity.Cinemachine.InputAxis.html#Unity_Cinemachine_InputAxis_Range
Implemented a proper version (I think?) of the A* algorithm, now it works pretty good
(I've slowed it down for debug purposes)
!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
• :question: Other/None
Duplicate script
thank u
So, I am attempting to work on a Top Down Point and Shoot game, but I've been running into an issue with occasional movement stutters whenever I move my mouse.
I put together a very simple project that is just a capsule with a basic movement script and while the dip in FPS is not as prominent as it was in Godot (60 FPS -> 45 FPS compared to 60 -> 7) it still happens.
What am I missing? One small note is that I do have a custom cursor setup as a crosshair.
you should probably consider using a phsics based movement instead
None of this seems to have anything to do with mouse movement so I don't think it's got anything to do with a slowdown when moving the mouse
It is literally the only script in the entire project, in that there is nothing else in this project to share other than this bit of code, unless you think a setting might be the cause?
I can do that, though I'm hesitant to believe it is going to result in anything different. I'll get back to you once I've moved it over.
If this is the only code in the project and you don't have, like, a billion triangles rendering, you should not be seeing any performance losses anywhere from this. You should use the profiler and see what's actually causing the problem because it's not this
Do you happen to have a gaming mouse with high polling rate (Hz)
It was causing similar issues for me
Yes, I do -- Were you able to resolve the issue?
I have a Razer mouse, I am able to change the polling rate from the Synapse app at least
At least 8000 Hz was causing lag for me
Same 😭 I guess I really need to get the Synapse because I also have 8000 Hz.
Do you have any concerns about releasing a game where gamers are going to need to reduce their poll rate just to play your game?
Oi, well.. I have a strong feeling this will fix the issue. I'm a little concerned months of work is going to result in people considering my game not competitive due to weird stutters and asking them to change their mouse settings accordingly, but I guess we'll see.
Thanks Adalwolf et. all for the thoughts and advice
Then again it might not even be the issue :D
I don't think it has anything to do with your game, considering nothing in your game even reads the mouse input at all
I think it's your computer
Again, check the profiler.
If there's a problem in the game, it will be there
I believe Adalwolf is on the right track because that was the exact issue the Godot community was talking about, in which Unity was brought up as an engine with a supposed fix. But at the same time Godot ended up having a supposed fixed as well and there are still reports.
It might very well be my computer, but I'd find it odd that this PC would be the issue as I'm not running on anything near a potato.
It looks like it was, I guess I just hope that my game is worth people reducing their poll rate 😂 Thanks again
I feel it's mostly a marketing gimmick anyway
Have you tried making this a build and trying it there? Have you tried it on other machines or asked someone else to?
hey im confused after reading this, will my unity game stutter for people with a high polling rate mouse? how do i avoid this?
does anyone know what im doing wrong?
you need to get your !IDE configured
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
• :question: Other/None
what?
i use vs code
great! get it configured.
But im not on the same device that i code on
what? just configure it on the correct device obviously. having configured tools is a requirement to get help here. and it will make your obvious compile error even more obvious so you can correct it.
how do i do that exactly?
my ide is completing code tho
it sends me to the website of vs code
with instructions for how to configure it
please actually make an effort to read the information instead of looking at the very first thing on the page and making assumptions.
click the link in the bot embed and it will take you to the page with the instructions for configuring vs code.
then once you are there, read that page instead of immediately clicking the "Download" button in the page header which isn't even part of the instructions
okay… now im installing the sdk
i saw some people saying you shouldnt use deltaTime for mouse movements, but i dont remember what they suggested instead, does anyone know?
they probably suggested just not using deltaTime for mouse input. there is no replacement for it, mouse input is already a delta from the previous frame so by multiplying it by deltaTime you bind it back to the frame rate and cause it to be stuttery, doing so also forces you to make whatever sensitivity or multiplier variable you are using need to be about 100 times higher
so instead of
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
do
float mouseX = Input.GetAxisRaw("Mouse X") * sensX;?
thank you
So happy right now. Learned so much today and managed to implement more into the project. Really hope the other collabs will be as happy as I am 🙂
hell yeah man
Day by day is the best 👌
@limber flower Last time coding was years ago haha. Very excited to be back with it.
Great hobby for sure.
i just started a few months ago
Show the inspector of the object this script is on
Can you expand the Rigidbody inspector and show more of its properties?
is it better practice to have the main game manager to
public CameraController cameraController; and set it in the inspector,
or to
cameraController = FindObjectOfType<CameraController>();```
Try logging myRigidBody.linearVelocity after you set it, see if the log prints and what it prints
One thing learned about coding is to stop giving up over frustration. We always get there eventually and it feels great!
Sometimes all it takes is a little more sleep or to step away for a bit haha
You should basically never use any functions that start with Find. Basically ever
i'm sorry log it to where? i'm just new to this stuff
I have
public enum playerState
{
firstLaunch,
mainMenu,
loading,
playing,
paused
}
public static class GlobalGameStates
{
public static playerState playerState;
}```
This is so I can keep track of the current state, and do things like check whether the game is paused from any script without needing to individually add the main game manager to every script that might need to check this stuff
Is this a sensible approach? Am I missing any obvious states or problems?
my goal is to be able to do things like
if (GlobalGameStates.playerState != playerState.paused)
{
##Various time based calculations and stuff that shouldnt happen when the player is in a menu or reading dialogue
}
A static class is acceptable if you don't need any of the functionality a monobehaviour can have, like storing references. It also avoids some of the problems of a singleton
If you need a monobehaviour for it, but don't want a singleton, then looking into the Service Locator pattern can be a good alternative
What cases might I need a monobehavior for it?
I don't anticipate needing it, the global states thing will hold things like the aforementioned playerState, and also things like the radio status (powerOff, messageWaiting, playerUsing, idle)
The reading and writing will be done by other scripts that are running monobehavior, I'm essentually just using this as a box full of the rare global variables I'll end up needing
but I also fully expect I'm missing something, if you can see a case
A monobehaviour is only needed in this case if you want to have inspector references on the manager. Which it doesn't sound like you need
inspector references? Like being able to go in and manually select "paused" for debugging purposes or something?
Not so much that, but for being able to drop a reference to your player object, or other important objects, onto the manager
In your case it sounds like you're not handling references to these things in your state manager, and instead its just focused on enums and other raw value data
well lets not forget about being able to use important functions like Update()
But in this situation a plain old class seems like the way to go for generic state storage
True, the life cycle functions won't be available to a static class. You can "fake" an awake through runtime initialize attribute, but that's it
Though I think this class is storing the variables and not really processing them
If my code is like
MyClass
{
MyMethod
{
SomeLogic;
AnotherComponentInMyGameObject.MethodInAnotherClass;
MoreLogic;
}
}```Will my code wait for `MethodInAnotherClass` to finish running before `MoreLogic` gets called, or since it's in a different component it will run parallel? I ask because in my case `MethodInAnotherClass` could take a while and `MoreLogic` only works if `MethodInAnotherClass` has run fully.
er no it waits
Yeah. There are edge cases where it won't, but that's when you're dealing with coroutines or async
Ok perfect!
ah, yeah that's the exact use case. It's storage I'd like to be accessible everywhere. I want the radio to beep every 15 seconds when theres a message waiting, for example
and I don't want it to continue when the player has the game paused
I could drag the mainGameManager script into radioManager and use that to check whether the game is paused, but I'd rather be able to just check if (GlobalGameStates.PlayerState == playerState.playing)
because I'll have a lot of objects with scripts like that, and doing so every time would get tedious
I think keeping your data storage class strictly as a storage class is the best approach. Keeps it simple, and means that any bugs have to be occurring in the classes that are changing the data only
so keep GlobalGameStates the way it is? where the only thing in there is C# public static ##Some data of some kind
or is a "storage class" a seperate thing I'm not aware of
in c# a static field needs to be declared in a class
Yeah. At most you can add this attribute if you want some initialization when the game starts, but otherwise have other classes change and process the data
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
I currently have those kinds of initializations in the Start() of my main game manager, so I think I'll keep it that way
Sounds perfectly fine
is there a way I can make the data in that storage class visible for debugging purposes?
custom editor window?
Yeah, you could have a custom editor window to display it
I'll look into how to do that, is it complicated?
Yes and no. If you just need to display variables and don't need it to look nice, then it's pretty straight forward.
Once you want to arrange buttons and have polished presentation, or have complex actions, it can get tricky
Not really, you can use OnGui or visual elements and just show the state of your static vars
https://docs.unity3d.com/Manual/editor-EditorWindows.html
The section titled "Implementing Your Window’s GUI" shows a sample
I recently made an in-scene level builder for my dungeon crawler using a custom editor window. Took about 2 days
nice!
and that indirectly answers my next question, the tutorial said the script had to be in a folder called "editor" but I didn't know if it mattered whether it was "project directory > editor" or "project directory > assets > etc > editor"
Any folder called "Editor" at any spot will do. The code in there will not compile in builds, and is only available in the editor
You can also use compiler directives to specify parts of your code that should only be included for the editor
#if UNITY_EDITOR
// only compiles in editor
#endif
(except when the folder is in an asm def)
is there some way i can set up a rigidbody so it isnt affected by external forces but will still collide with other objects
why that happens ??
did you read the message at all? script has outdated api stuff that needs changing
You're using older syntax in your code, or Unity is falsely picking up one of your variables from their name and judjes it "obsolete"
oh so i need to find another tut ig
Most likely the latter, since that bird tutorial is not ancient
I learned this lesson the hard way, after not using namespaces
Post the code so we can see what's going on with it
The code cannot compile at all (it is invalid) so you should disregard the message until fixed
!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
• :question: Other/None
^^ Configuration options
should i just click yes
No, and configure the code editor first
im stupid tbh
how to configure
Scroll up
ha ??
"IDE Configuration" message in this conversation above
i spammed no and it worked
using UnityEditor;
using UnityEngine;
using System.Collections;
public class GameStateInspector : EditorWindow
{
[MenuItem("Windo/Game State Inspector")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(GameStateInspector));
}
void OnGUI()
{
GUILayout.Label ("Game States", EditorStyles.boldLabel);
GUILayout.Label("Player State: " + GlobalGameStates.playerState);
}
}
I think I got it, how do I actually open the window? the tutorial doesn't actually say, it just says it will "create it"
Using GetWindow should be opening it, if that's not already the case, so make sure this method is being executed
how can I do this? an editor script can't be attached to anything from what I can tell
See if you can Debug.Log() in that method
Depends on your keyboard layout, cannot answer
i get that * one
not the one that is used
that's just a font
Fix the typo in Windo and it will show up in the window tool tab at the top of your editor
Ah, the fool's "missed a character" type bug, thank you! That got it, works great now!
Capital Eight
that is the up one
Then you've got a different keyboard layout and you'll have to look with your eyes and see where it is on your layout
- OH SO THAT WORKS
Any idea on why this particular gizmo isn't drawing?
i wrote wrong one here **
why im facing everysingle problem idk lol
I would encourage you to read thoroughly and check your available options before asking strangers
You didn't write the wrong one, it's Discord interpreting a * at the beginning of the line, and displaying it as a bullet point. It's a Markdown formatter
as a general rule that will serve you well in programming
i do i swear
idk what is rlly happening with me
lemme find another recent tut
i started to hate that lol i spent 1 hour trying to do simple stuff
why i cant find any unity tuts toooo
your first hour with literally any skill is going to be poor, that's typically how skills work
don't assume you have a problem, assume you are missing knowledge, and go forward with that assumption instead
It helps you mentally, in that you don't feel like your computer is trying to kill you
and it helps the people trying to help you, because they feel like you're asking for information and not like you're blaming the program for something
i dont mean that i meant that wasting 1 hour just trying to find a tut is crazy
example
"wasting 1 hour just trying to find a tut is crazy"
- is complaining
- gives the impression you don't want to be here, doing this
- generally unpleasant and not calm
People here are not being paid to help you and have no obligation to do so
"Can anyone point me in the direction of a good unity tutorial for a beginner"
- polite
- more calm
- still communicates what specifically you need
mb
Interested in Unity but not sure where to start? Start here! In this tutorial, you can choose your own path to learn about Unity, discover what it can do, and explore ways to learn it, depending on your goals and interests. We'll even guide you through installation if you haven't done that yet.
try this
thanks brother or sister
Very welcome
General format for asks is something like
I'm trying to [task]
Im doing so by [The specific system or options]
I expect it to [Expected outcome] but instead it [whatever is happening isntead]
and also generally comes with the expectation that you tried to use google first
thanks ♥♥
This grinds my gears. People here have no obligation to do so and yet are helping this guy who is complaining. Makes me wonder if I'm doing the wrong thing.
what did you mean by gizmo isn't drawing, anyway?
either way, this isn't a code question, it's a general unity question and should probably be somewhere else, like Unity Talk
In general, people answer questions they know the answer to. "Why won't a gizmo draw" is a more complicated question than "How do I type *" so more people will answer the latter
Anywho, I'm assuming it's a custom Gizmo you're expecting to see, post the !code for it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
This gizmo isn't appearing in the editor scene :/. I have tried the following:
- Reset layout
- Clicked Gizmo button on/off
- Ensured default layer is viewable
using UnityEngine;
public class respawnManager : MonoBehaviour
{
public GameObject objectToSpawn;
public Transform lineStart, lineEnd;
// gizmos
public Color gizmosColor = Color.blue;
public bool meshPreview;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
private void respawn()
{
//respawn stuff
}
// Update is called once per frame
void Update()
{
//stuff
}
private void OnDrawGizmos()
{
Gizmos.color = gizmosColor;
Gizmos.DrawLine(lineStart.position, lineEnd.position);
if (meshPreview)
{
if (objectToSpawn == null)
{
Gizmos.DrawCube(lineStart.position, Vector3.one);
Gizmos.DrawCube(lineEnd.position, Vector3.one);
} else
{
MeshFilter modelMeshFilter = objectToSpawn.GetComponentInChildren<MeshFilter>();
Mesh modelMesh = modelMeshFilter.sharedMesh;
Vector3 modelBounds = modelMesh.bounds.size;
Gizmos.DrawMesh(modelMesh, 0, lineStart.position, modelMeshFilter.transform.rotation, Vector3.one / modelBounds.x);
Gizmos.DrawMesh(modelMesh, 0, lineEnd.position, modelMeshFilter.transform.rotation, Vector3.one / modelBounds.x);
}
}
}
}
Hope this helps
hint: check your color
Your alpha seems very low here
!thanks wow I'm surprised I didnt catch that >.< Thank you 😄
Theres no bot for thank yours here like the web dev discord :/
void abc()
{
othergameobject.setActive(true)
abcxy...
}
is there any scenario that the onEnable in the other gameobject run after the abcxyz
no, OnEnable should run immediately upon being enabled via SetActive
okthanks
Unless that object has a parent that is still inactive
what is wrong if someone can tell me
you need to get your !IDE configured 👇
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
• :question: Other/None
oh lemme see how i can fix that
that may be because you're using vs code not visual studio
they are completely different programs
im using visual studio code
that's what i said
workloads are for visual studio not vs code, did you suddenly switch or are you still looking at the wrong information?
shouldnt i download visual studio ??
i mean it is better than vs code, but you can use either
then yep i switched to it ig
then just follow the instructions in the guide
if you on vsc search the extension place for unity
guys can someone help me: I dont understand why its always a random offset or like its not always hanging the same. It should always be same ledge hanging:
{
if (ledgeDetected && canGrabLedge && !isHangingOnLedge)
{
canGrabLedge = false;
isHangingOnLedge = true;
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;
rb.simulated = false;
Vector2 ledgePos = ledgeDetection.GetLedgePosition();
Vector2 hangOffset = new Vector2(isFacingRight ? -0.8f : 0.8f, -0.75f);
Vector2 hangPosition = ledgePos + hangOffset;
transform.position = hangPosition;
climbBegunPosition = hangPosition;
Play(Animations.CLIMB, 0, false, false);
}
if (isHangingOnLedge)
{
//Play(Animations.CLIMB, 0, false, false);
if (Input.GetKeyDown(KeyCode.Space))
{
PerformLedgeJump();
}
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
why is it darkened like that
because visual studio doesn't know that a component is calling that method so it thinks nothing is referencing it
oh thanks
fr visual studio is lifesaver
the other one was trash
i actuacctly did wrong code
i mean, vs code can do intellisense and error highlighting too provided it is configured
for me vs code was trash experience
because it wasn't configured
made me give up on two tuts thinking smth was bad experience
and u right
lol cuz i did wrong stuff before the whole project is ruined
can someone help me. so the character always gets a random offset and i dont understand why
why velocity doesnt work ??
read what it tells you
yes
but idk how to use linear velocity
why not? you know how to spell it, right?
by pressing one key after another in such an order that it spells that word
u made me learn alot thanks :>
anyone know why i move side to side so fast im new please put it in simple terms
fr thanks alot guys u helped me in my start cuz im stupid :>
you need to get your !IDE configured 👇
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
• :question: Other/None
Because 500 is a lot
i changed that and it did nothing
Did you change it in the inspector
change it in the inspector
whats the inspector
The place you set variables
should they both be the same
the thing on the right
You should really know what an inspector is before asking here.
!learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
like i said im a beginner and im learning on my own i just started yesterday and have been watching youtube videos
thats why the chat says CODE BEGINNER does it not lmao
just because it is a beginner channel does not mean you are not still expected to put in effort to actually learn how to use the tools you are using
And that's why you've been directed to Unity Learn so you can understand how to use the program
thats why im asking questions
If you don't understand the very basics, that Unity courses provide, you won't be even able to understand help provided. That is what is happening now.
and it is also why you've been directed to the unity learn site where you can go through the pathways to learn what everything is and does in a structured way instead of wasting your time waiting on everyone else to spell out every single thing you need to do
You should at least know the editor ui. How can we help you if you don't know what buttons to press?
so since i dont understand how to do something u gotta be a jerk when im still learning
No one is being a jerk. This common sense really. At least go over the editor ui and the basics of working with it. Then we can move on to fixing your issue.
Since you don't understand how to do something, you were linked to a place to learn how to do that thing
providing resources to learn how to do things yourself is being a jerk?
And then you've decided to take offense to that
The inspector is the thing in the UI where you'd drag scripts onto a game object
this isn't learning, this is you hoping to get the hang of it miraculously without taking the proper steps to actually learn
Btw it says code beginner. Not just touched unity for the first time beginner.
ok i get your point
finished first tut time for 3d tut
then some simple projects
strange i didnt find any good 3d tut
i think time to make the things i want to make
is there a difference between normalize and clamping ? Dont both set the value on a range basis of -1 to 1 ?
normalize usually implies taking the full value range and remapping it to a minimum and max, while clamping is just limiting those values
like the actual max of the value may exceed the clamp
so normalize "converts" the full value range into a min max allowing for any value, while clamp firmly restricts going out of range
Pretty much. Normalizing just makes operations easier when we convert it to some 0-1 range usually
How can I create multiple versions of my method? Like how if you use instantiate there are multiple variants with different options for variables.
is normalizing always 0-1 by default ? So for example a health bar meter being 0-100 (0-1 values for a slider example), where as in my case Im clamping due to needing a range of motion -1 to 1 (left and right )
ClampMagnitude ensures the length of the vector will be mo greater than 1.
Normalize ensures the length of the vector is 1.
Normalizing is also slightly faster than ClampMagnitude for boring math reasons, but it's a negligible amount
ty
Note that this applies to vectors. Normalizing a float isn't really a thing, so a slider value would not be normalized
Create multiple methods with different parameters but the same name
These are called "overloads"
Screencoordinates are considered normalized, as you're usually dealing with 1,1 top left/right of your sceen and 0,0 being the bottom right / left
but vector normalization is something else yeah
if gobj parent is disabled then when parent.setActive(true)
does Start in child or parent get called first or is it just random
awake/start/onenable
if the object you're instantiating is disabled by default, usually those methods won't run
as far as start and onenable goes... need to double check the awake
parent is disabled at first in editor, later in the game it get setActive, im not sure the child or parent get called first
I don't usually rely on the execution ordering of the parent, but if the parent is disabled then the children should also be disabled, so none of those methods should be called anyway
i understand that but later in the game parent get enable back
Later on yeah they should be called, as far as onenable and start goes
onenable -> when the script becomes enabled
start -> first time the script updates
but my main point is does parent's or child's get called first
cause when enable parent, child is enable too
Obviously I'd say parent, but again, I wouldn't rely on the object hiearchy execution ordering.
Awake, Start, and Onenabled have their own execution ordering that I would suggest to rely on instead
Awake -> OnEnabled -> Start
i think smt thing wrong there, awake should be same order with onEnable?
but parent and child atm can be toggled, so cant settled with awake or start, both use OnEnable, so im just trying to know sure if parent or child get called first
Ideally Awake should be used with those with no dependents, and otherwise use OnEnabled/Start.
If you have a chain of dependencies, you can change script execution ordering in the project settings, but I suggest try not decoupling out your objects too much if that happens.
idk, i just wanna kno if parent or child get enable first, if you say parent then imma take ur word for it
I said I would expect it to, but considering the documentation doesn't really talk much about the parent/child execution ordering and more about the ordering of these functions, I would suggest just use those along with the script execution ordering preferences
Because I know for sure the ordering of your elements on your scene are order independent for when they execute when loaded, so I wouldn't trust it at all
I am trying to make a audio system for my game, so different scripts can play sounds. I am using the camerashake to determine when to play a step sound, but I don't know how to make sure it plays consistently. This is my code: https://hastebin.com/share/xuvosavuwo.java, https://hastebin.com/share/moxebapasa.csharp
So the thing with footsteps and other clips you probably want to be used consistently is that they should be looped on the audio clip source itself and instead of destroying after the length you should destroy/disable when you stop moving
Im trying to make a game for a college project 2D platformer and my character wont fall below 0.85 even though my groundcheck is false could anyone help
The reason the audio clips are spawned like that is because the camera shake speeds up or slows down depending on how fast the player is moving. So if the walking sound has a consistent looping the audio won't match the video
overall you shouldnt be spawning an audiosource every time you want to play a footstep. You need to control the source and play it when you need to
Can't work with anything without a script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Besides the footsteps, I think what you have here is fine. It's just for something like footsteps I wouldn't personally use one-shots for but instead have a dedicated audio source for.
However, if this is like a small project and you don't care about the absolute optimal setup, I'd say do what works for you
Sorry, I didn't provide enough context in my question, I'm having an issue with the setup, the sounds are sometimes being played twice at once.
So where does this 0.85 come from? I'm not understanding what this value is, nor do I see anywhere in the code that you are limiting to this unit
apologies i want my character to fall when approaching an edge but for some reason its y value will not fall lower than 0.85 and float above my groundLayer
If you are applying the audio multiple times in a frame, or very close to each frame then you need a way to keep a history of those clips which is pretty common to prevent stacking the audio too much
An idea is when you create an audio source for a clip, throw the clip into a dictionary with the previous time played, so next time you play an audio clip you check if its currently in the dictionary and compare against the current time and the time it was last played
Would this work with my current setup?
if (sinX > 0.99 && !stepped)
{
SoundManager.instance.PlaySoundFromList(steps, player.transform);
stepped = true;
}
else
{
stepped = false;
}```
i moved a script to a different folder and suddenly this happened
script in question is not refered to in any other script
Well, your code there seems to implement some coyote time or w/e lastGroundedTime is supposed to accomplish, but otherwise rigidbody component should apply a gravity on the y axis. I'm not seeing anywhere in this code that prevents you from falling an amount of units unless you're being grounded somewhere so I suggest to debug.log your code out more
nothing seems to be broken so im just going to ignore this and hopefully it doesnt bite my ass later
Either something was using explicit pathing, or unity editor just trolling you which can be fixed with a restart
Visual Scripting stuff it seems so if you're not using it dont worry
Any way to link your audio clip and some time variable that you can compare in your methods there
private Dictionary<AudioClip, float> clipCooldowns = new();
public void PlaySound(AudioClip clip, Vector3 position, float cooldown = 0f)
{
float currentTime = Time.time;
if (clipCooldowns.TryGetValue(clip, out float lastPlayedTime))
{
if (currentTime - lastPlayedTime < cooldown)
{
return;
}
}
clipCooldowns[clip] = currentTime;
//Rest of code
}
Just as a fallback, but if you're playing based on a curve then it is dependent on how you play it
That can be tricky, though. I'm sure some sounds can play more than once at a time. They'd have to figure that out. You could check if the sound (you're attempting to play) is below a max stack limit . . .
I think I refined it a bit and it should work:
// check if sound has been played
if (clipCooldowns.TryGetValue(clip, out float lastPlayedTime))
{
if (currentTime - lastPlayedTime < cooldown)
{
return;
}
else
{
clipCooldowns.Remove(clip);
}
}
else
{
clipCooldowns.TryAdd(clip, currentTime);
}
clipCooldowns[clip] = currentTime;```
But I'm thinking, if I were to do what you said and use one audiosource on the camera object, how could I do that and still play the sounds more than once at a time, the time between the sounds and the time between each step need to be proportional.
Wasn't one of the questions on how to prevent it from playing it more than once? ;p
Ideal solution: use a single audio source, loop it, and change the audio speed if you need to play it faster
i have a script that allows the player to jump in my game when it detects tag "ground" it works on a cube but not on terrain
does terrain have a diffrent way to detect things or should i just add a box collider to my entire terrain
this is not exactly a code question; don't crosspost, let's discuss in #💻┃unity-talk
layers != tags
ya
so think real hard about the question you've asked and what you are actually doing in your code
the code works when i use a regular cube
its in the right tag and all i just switched from a cube to a terrain
notice how that object is actually on the Ground layer
and you aren't doing anything at all with tags in your code
do you mean like physically touching it
no
the navmesh agent?
still no, look at the object you've screenshot. read what your code is doing, read what i've said about tags and layers. then look at the terrain object
the code checks for layer ground
the cube is layer ground + tag ground
the terrain is layer [something else] + tag ground
Just vibe checking, this works fine right?
if (SelectedContent is not ScriptableDevice device) return;
//thing with device
dw about the inproper null check
provided you are on a unity version that supports that, yes.