#💻┃code-beginner
1 messages · Page 821 of 1
you don't "set" anything like that, you just use the player's rotation rather than the camera's in your movement code
oh ? u dont need to tell it wich side of the player modle is farward ?
you just rotate the movement direction appropriately
^ We can rotate user input as needed (e.g. using the players rotation)
new issue ive never had before my capsule colider is making my capsule flout ???
is that a child of the model or is it the parent?
look like this the commponets are attached to the parent not the mesh its self
okay so that is the parent of the mesh. in that case make sure that you don't have any collider on the mesh as well and also check the collider for the ground object. you can also enable gizmos in the scene view to actually view what it looks like in the scene
my only other colider in the scene is a flat plane lol
could it be the camera ?
also tested witht he box colider turned off ??? and still did it
AAH found it
thank you
that was scuffed
it was a player controler component cuasing problems
if you mean a CharacterController, then yes don't mix that with the Rigidbody
lol
i jsut watched one of the most usless tutorials on the planet didnt relize i left that there
I've noticed intellisense is taking a painfully long time to initialize when opening a new script. Like, sometimes it takes 30 seconds for errors to pop up. Anyone else get this?
Can happen in bug projects. What ide are you using?
And is that 30 sec after the script is compiled or including that time?
Visual studio 2022, and not sure on the second part. I don't think there is script compilations happening.
Are you creating it via unity or the ide?
The script? Just opening it from unity. These are scripts being brought over from another project, so maybe that's something?
Technically, unity needs to compile the script and add it to the csproj/sln files for ides to see them as real project scripts.
How are you bringing them from the other project? Darg and dropping into the editor or..?
Yeah exactly that. I have two projects open, and am dragging a script from one editor to the other (didn't even think that was going to work but it did lol)
On another note, has anyone ever looked at their code and gone "bruh, why did I make this so convuluted?" That's kind of me right now XD
Thats step one to making it good
For some reason this code is rotating the gameobject along the wrong axis and I have no idea why: ```using UnityEditor.ShaderGraph.Internal;
using UnityEngine;
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
//Get Mouse Input
float mouseX = Input.GetAxisRaw("Mouse X") * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
// Rotate Cam and Orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
Well, that should presumably trigger a lot of script recompilation, during which it's only natural that the ide would not work correctly.
Neither do we. At least without seeing more context.
One question for you is whether you really want them to rotate in world space or maybe in local space?
whichever works.
This code was working before but as soon as I merged the branch I was working in into the main branch some of my code just broke
Well, gotta figure out what changed. 🤷♂️
There's not much we can do about it unless you start providing more details/context.
Okay after a little bit of testing I realize now that the code only works in certain scenes
Not sure if i'm doing this an efficient way, but i'm trying to have my game be able to read which 1 of 4 materials have been randomly selected to a gameobject. Though I don't fully understand what i've written, I have the random color changer working as intended, how do I make it so the game can actually detect which color has been selected? (preferably using my currently un-used bools)
private Renderer ColorRenderer;
public bool isblack;
public bool iswhite;
public bool ispink;
public bool isyellow;
private void Start()
{
ColorRenderer = GetComponent<Renderer>();
if (PossibleColors != null && PossibleColors.Length > 0 && ColorRenderer != null)
{
ChangeToRandomColor();
}
}
public void ChangeToRandomColor()
{
int RandomIndex = Random.Range(0, PossibleColors.Length);
ColorRenderer.material = PossibleColors[RandomIndex];
}
}
What do you mean by you don't fully understand what you've written
I found out how to make the colors switch through google, i'm not very experienced in coding. It works, I just don't fully understand why it's working.
I loosely understand it, I think my current understanding of how arrays/libraries function is still lacking a bit. I just started learning to code a month ago
so ask it to explain it to you
what is even the point of those bools
also the method is public, if any other scripts call it and somehow ColorRenderer is null... you will get null ref anyway or if array is empty
why is my regex only detecting the dark blue selection, but ignoring the light blue?
( i want it to do both )
Where does target come from?
My LS doesn't seem to recognise it (I assumed it was a class member), just unity inject it directly into the method scope itself?
Or is my LSP setup just not detecting it?
inheritance
So it is a class member and my LS isn't detecting it
weird
thanks
yeah that's on my end, I can see it in the docs 👍
in your defense when i googled it to double check it only gave me the api post for Unity 5.3's version for whatever reason lol
if you need any further help hitup #↕️┃editor-extensions
could i have some assistance? :3c
(people here might not be experienced with regex)
it's detecting both in a single match, greedily?
do you need them to be detected separately?
yeah yeah
is that what it means by greedily?
make the quantifier lazy, .+?
greedy means it matches as many characters as possible first - it only backtracks to consume less if it can't make a match, but it won't backtrack to make more matches
lazy means it'll match as little as possible first, and it'll backtrack to consume more if it can't make a match
now its not detecting the 2nd part
ah, your regex is not global.
oh, there, but how do i make the first match go up until the next match?
perhaps make the regex end at a )?
not sure what exactly the goal is
you could also make it stop at the next comma or the end, like (?=,|$) but that might not work if the match is in the middle of another string
or maybe (?=\))
what's the overall goal?
trying to take a string input, see if it has R(stuff1, stuff2), then extract it (which i've done)
my current goal, is to extract stuff1 and stuff2, which could be literally anything
the example input is R(R(0, 500), Y), to make sure the operations take nesting into account ( since stuff1 is also a R(stuff1, stuff2) thingy )
you probably want to not use matches then, since matches can't overlap
you could use capture groups instead
c# doesn't support recursive regexes, barely anything does, rip..
recursive nesting is kinda a hard thing to do in regex
dammn
if you can make the assumption that R( always begins one of these and they're always valid, you could write a parser relatively easily without backtracking
though the difficulty would depend on what exactly is allowed inside
hmmm, could i loop starting at there, and then go until it finds a ), but skips every ) for every additional ( it finds
and then once it ends, extract the substring
and perhaps do something similar for the ,
It’s your game so if you think it’s what you want by all means continue but could be worth considering if players would want to do these typed expressions in the first place? I wonder if some sort of drag and drop / puzzle piece kinda system might be easier for you and them (im imagining stuff like scratch coding or human resource machine)
just throwing it out there no judgment however you go
oh its actually a thing you type in the unity editor for asset-creation, and the expressions get resolved in run-time
oof if it's user input then it's gonna need error handling too...
you're having problems with pushing to the repo, or what exactly?
or if you want to ask about code, you could use pastebin sites as well
Just go on and ask
trying to make this shotgun pickup system but its not working
gonna need to give some more info than that
right no you have to say how it's not working
literally nothings happening
like i start the scene go up to it and press e its like i never typed out the code in the first place
Did you add the script component to any object
the script you linked isn't checking for E
...link the one with issues, man
one refrences the other yall ain give me time to send the links 😂
you were supposed to do so before coming to ask, so all your info is consolidated in a single message
do some debugging then, see which ifs are being reached
you don't seem to be changing hasBeenPickedUp anywhere
...well, yes, that's what debugging is.
there's multiple steps there, you gotta figure out which step isn't working. we aren't sitting behind your shoulder, we can't do this part of debugging for you
once you identify which step isn't working, we can go from there
If hasBeenPickedUp never gets set to true, the gun would never activate so im going to just figure it out myself
you did say nothing is happening so i assume Pickup is never being called, as that would cause some stuff to happen
the problem is i cant figure out why
we can help you figure out the why. right now you need to figure out the what
add Debug.Logs in each if, see which are being reached and which are not
yea give me a min lol
(also make sure you don't have errors hidden in the console tab)
true i did disable errors because i turned off navmesh for testing
jesus christ it only works when the regid body is kinetic
but i cant use gravity so im not sure how i can make it a regular world object
Wdym can't use gravity? You can disable gravity on a non-kinematic rb
Is there any sort of production assert in unity?
I know it's a game engine but there's also a lot of people doing non-games who that would benefit lol
You can configure the asserts to be enabled in builds
as in Debug.Assert?
yes
Thanks
lol but if i disable gravity the shit jus floats in the air
i fixed it thanks anyway though
Hi everyone, I have been building an educational mobile game "Tappy mole" for kids, this game teaches kids social etiquettes by performing different fun activities like brushing teeth, eating healthy food, getting proper sleep, keeping clean etc.
One of the features in "Tappy mole" is voice playback system similar to the popular game "Talking Tom" where the game character records the player's voice and then plays it back.
There is once issue that is taking my night's sleep away. that is the recording is triggered by the game audio as well, so sometimes if the game sound is loud the mole records it and plays it back. I have tried many ways but couldn't solve the problem. I’d appreciate any guidance on how to tackle it.
My requirement is that the game should start recording if the loudness has crossed a certain threshold and it must ignore the game audio itself, so the infinite feedback is not triggered.
I have provided my audio input script and a screen recording of the game. in the video you can see that when I pick a soap, it makes a sound and the mole is triggered and starts listening.
thanks
Maybe you can compare the system volume to the threshold, so when the volume goes up, also up the threshold. That would be like a simpler fix. Another approach is to actually check for voice recording, so if its not identified as voice, dont record
but wouldn't increasing the threshold result in stopping the recording?
how do i use lookAt in 2D?
so for example, i can make the player move to the mouse
if your surround is too loud, you need to up the volume threshold, so it only starts when something is relatively louder than your music. You could also check for the lengh of the recording. So if its only oneshot sfx that triggers it, maybe do not record anything below a certain amount of time
it already does that. it ignores recordings below 2.5 s, and also if the threshold is high the user has to speak very loudly.
That is the solution for the current setup. You could also just avoid loud sounds entirely to avoid this situation. There are many ways. But in the end, if you want to keep as is, you need to recognize voice from sfx
lookat sets the forward vector, but in 2d you generally need the forward vector to point away from the camera
you would assign to the up or right vectors instead
id on't think i get what you mean
which part exactly?
assign the up or right vectors
assign to transform.up/transform.right, depending on which one is the "forward" of your specific object
and while I see it, do not cross post... remove it from one or the other channel
So things do not get cluttered up
they were redirected here.
yeh, was more about cleaning things up, otherwise someone could still answer over there for whatever and you start two convos about the same topic.
but my forward consists of up and right
not sure what you mean by that, could you rephrase
mm
i think i worded my question wrong from the get go
so i wanted to make a "dash", when on pressing space the player would look at the mouse, move fast to the mouse and then snap back into "normal" mode
i tried using this code, but it had almost the opposite effect
if you're in 2d, transform.LookAt and transform.forward are not super meaningful.
you could get a direction vector from the current position to the mouse position (after converting to the same space) and set the up/right vector to that
huh?
-# i am pretty slow, sorry on that
i'm not going to rephrase the entire message to be a paragraph long
please specify which part you don't understand
so i can elaborate on that specific part
how can ou get a direction vector from two positions?
subtract one from the other and normalize it, though for the usecase of assigning to transform.up/right/forward i think it normalizes it for you
adding/subtracting a vector geometrically looks like changing the origin
so if you have 2 positions A, B, then A - B looks like moving the origin to B - it's asking what A is from B's perspective, aka the vector from B to A
the magnitude of that vector is the distance, and the direction of that vector is, well, the direction
{
LevelCollection levels = new(new(),new());
if (unlockedLevels != null)
{
foreach (LevelData level in unlockedLevels)
{
levels.unlockedLevelIds.Add(level.id);
}
}
//Add next level IDs
if (nextLevels != null)
{
foreach (LevelData level in nextLevels)
{
levels.nextLevelIds.Add(level.id);
}
}
string json = JsonUtility.ToJson(levels, true);
File.WriteAllText(SavePath, json);
Debug.Log("Save");
}
public void Load()
{
if (!Directory.Exists(SavePath))
{
File.Create(SavePath);
return;
}
string json = File.ReadAllText(SavePath);
LevelCollection levels = JsonUtility.FromJson<LevelCollection>(json);
//unnlocked level
foreach (int id in levels.unlockedLevelIds)
{
if (allLevels.db.TryGetValue(id, out IdObject level))
{
unlockedLevels.Add((LevelData)level);
}
else
{
Debug.LogWarning($"Unlocked level with ID {id} not found");
}
}
//next level
foreach (int id in levels.nextLevelIds)
{
if (allLevels.db.TryGetValue(id, out IdObject level))
{
nextLevels.Add((LevelData)level);
}
else
{
Debug.LogWarning($"Next level with ID {id} not found");
}
}
}
void OnDestroy()
{
Save();
}```
I havent fixed issue from yesterday. this is presistant singleton and is only one who knows about that file. Still getting IO Sharing violation on path
So you are getting an exception that says that? Which line does it point to?
It points at save call in on destroy. In save it points to writealltext
Does that happen when you call it from somewhere else, or only via OnDestroy, or both
Could put a debug.log in the start of the Save method to see if it's triggering twice or something.
@verbal dome Triggered once and works, if load isn't called
Didn't answer my first question
When Save throws the exception, was it called from OnDestroy or from somewhere else? Look at the stack trace in the console with the exception log selected
The exception means that multiple things are trying to read from/write to the file at the same time
@elfin pike So close applications that might have that file open, if doesn't work, restart PC
That's the thing these also didn't work
OnDestroy not at fault, I placed in start and gave same result. It's something to do with 2 functions. Haven't tried to call same function twice, from observed second function always get error, doesn't matter if save(), load() or load(), save()
using Unity.VisualScripting;
using UnityEngine;
public class TimerAndCheckpoints : MonoBehaviour
{
[SerializeField] float currentTime = 0f;
[SerializeField] bool timerRunning = false;
float numberOfLaps = 0f;
float checkpointsPassed = 0f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
timerRunning = true;
}
// Update is called once per frame
void Update()
{
if (timerRunning == true)
{
currentTime += Time.deltaTime;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("LapGoal"))
{
if(checkpointsPassed >= 10)
{
numberOfLaps++;
Debug.Log("Time: " + currentTime + " secs");
currentTime = 0;
}
else
{
Debug.Log("fucked up");
}
}
if (collision.CompareTag("Checkpoint"))
{
Debug.Log("went through a checkpoint!");
checkpointsPassed++;
}
}
}```
Hi guys! I'm working on a small top down 2d racing game. It's a school project, nothing crazy. I'm trying to get checkpoints to work, but there's a big problem. I want the checkpoints to be prefabs so i can place them however i want (using the "Checkpoint" tag. Problem is, you could just go across the same checkpoint 10 times in order to pass many enough to finish the lap, and these checkpoints are meant to force the player to go through the whole track. Doesn't add up.
The easy way would be to give each checkpoint an identity so it knows which checkpoint in the order it is and check if its been passed. If it has already been passed, just make it not register anything until the next lap begins. However, i dont know how to do this with prefabs.......
TL;DR trying to make checkpoints using prefabs. cant figure out how to check if the player has already passed a specific checkpoint (in order to deactivate it somehow and prevent checkpoint spamming)
thanks for any help
Them being prefabs doesn't prevent you from giving them ids
How would I do that?
But you could for example add a script to the checkpoints that tracks if that checkpoint has been passed or not, and ignore it if it has been
The same way if they weren't prefabs? Add a script that has an id field and give each of them a different id
"I dont know how to do this with prefabs" implies that you know how to do it if they're not prefabs
yeah
well do it the same way
so i just do it the same way and turn it into a prefab with the script still attached
nice
chat i forgot how to reference a variable from another script in my script help ✌️
Use GetComponent to get the script on the target object. Then with that, you can access any public fields on said script.
Hey ! I'm omega beginner on unity and i'm trying to make a first person controller camera player, but for some reason nothing works ( i'm sure i did something wrong but i can't understand why ) and when i try to copy a script nothing connects to it ( like some variables don't connect or something ) i'd be sooo grateful if anyone could help me 🙏
what do you mean by "connect" exactly?
For exemple, my " monobehaviour " seems to not be linked the same way since it's not lighting up 😭 i assume lighting up means it works
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
I only coded in HTML and CSS before so i understand the logic a little bit but now i'm super lost
You need to setup your Visual Studio ☝️
oh alright i'll try that !
In documentation, it's says, that function open and closes file automatically, why it doesn't close for me.
uhh so just started learning on my own and i got a question so why is there f after the value? float myFloat = 0.58f;
To denote it's a float instead of a double
unity will think its a double if i dont specify?
its not a Unity thing
the reason why we use a f to indicate a float and not a d for double / why we don't just use a double instead of float lowkey comes down to arbitrary decision making stuff for reasons and whatnot
it just is what it is
Maybe try manually closing the file and see if the error goes away. If it does, then it would seem there's an issue with that function or the documentation is wrong.
If there's still an error, then trying to investigate why it's not closing is folly
c# will know it's a double if you don't specify
we use floats, floats need an f
decimal numbers in C# are doubles by default
why though? arent both like same?
no
No
Have to find how to close it, because File class doesn't have function for closing
no, floats are 32 bits, doubles are 64 bits
floats are "single precision" (hence why the .net type is System.Single)
doubles are "double precision", double the size of floats
there are halfs, quads, and octs too
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
Try using a stream writer inside a using statement like the examples here
tysm
the other two answers are good but just in normie terms for gaming we generally just either use int's for when we need to care about precise numbers and float's when we don't. the value of other number types is far more niche compared to other programming usecases (eg. banking stuff can't use imprecise numbers lmao)
you do have to keep width in mind a bit
if you need to handle precise integer values in the trillions you can't use an int
For most reasonable human-scale numbers float is fine
idle games 
And since humans are meant to play video games, most video games use human-scale numbers
Thank tomorrow will give update, but very sure it will work. Issue looks like I have 2 streamwriters trying to access one file, one from load and second one from save
two ints ah ah ah 🧛♂️
For everything else, there's BigInteger
https://github.com/keiwando/biginteger
-# the other day i saw a video of someone scoring larger than graham's number in opus magnum...
-# (claimed to, at least. i did not watch the full video)
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("LapGoal"))
{
if(checkpointsPassed >= numberOfCheckpoints)
{
numberOfLaps++;
Debug.Log("Lap " + (numberOfLaps) + " Finished! Time: " + currentTime + " secs");
currentTime = 0;
}
else
{
Debug.Log("either fucked up the code or i didnt drive thru all the checkpoints");
}
}
}```
do you guys think having it be a OnTriggerStay function would be better? It sometimes doesn't want to register. (it's the checkered board.)
and yes i knwo the graphics are misaligned but honestly who cares, I'll fix it later
if its not registering there is probably another issue?
onStay can work but may inadvertently run something more times than needed without proper safeguards.
how are you moving them
through transform.rotate and transform.translate
yeah thats why its not registering properly
The car isn't very fast though, so I don't see why it would miss the pad
you're essentially teleporting by using Translate
yeah
skipping the physics and let it catchup rather then the opposite (let the rigidbody drive the transform)
you need to move rigidbodies with their appropriate functions
AddForce or set linearVelocity yourself
Idrk if i would deem learning that as worth it since it's for a school project
I mean, it would help me with future projects I care about more if i learned it now buttt..... idk it seems kind of hard to learn
Well, it's the solution to your problem, so you have to decide if this problem is enough of a dealbreaker
Or if you can just live with it
and literally takes like a few minutes.. there isn't anything extra to learn lol
the entire point of school is to learn 😭
in most cases the direction and speed passed to Translate fits exactly into linearVelocity (minus the TIme.deltaTime since physics has its own time)
the only difference is you're use Rigidbody component rather than Transform
why is this showing rb is not assigned T_T
did you assign it ?
right now what I'm doing is that i have 2 variables, one for steering amount and one for movement amount. if statements check what keys are being pressed, and the values of said 2 variables are changed accordingly. afterward, they get passed into the transforms.
at the beginning of the loop, they are cleared again so the car doesnt just keep moving forever
how do i do that?
inspector usually?
Because the variable rb of NewMonoBehaviourScript has not been assigned. You probably need to assign the rb variable of NewMonoBehaviourScript in the inspector.
i do understand i could just switch out the movement variable with a similar one for linearvelocity
but i dont get how i would handle the turning
the movement variable?
How are you handling turning now?
transform.rotate
you can technically still use that
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.MoveRotation.html
Or just keep using that, if you don't intend to use torque or anything a point-to-point rotate isn't going to break things much
using UnityEngine;
public class Driver : MonoBehaviour
{
//creates´variables to be redefined later on.
float steerSpeed = 0f;
float moveSpeed = 0f;
float steerAmount = 0f;
float moveAmount = 0f;
float grassSpeedReductionMultiplier = 0f;
float grassTurnReductionMultiplier = 0f;
//makes another variable used to localize another script later on
collisionscript collisionChecker;
void Start()
{
//localizes another script containing the collision checkers
collisionChecker = GetComponent<collisionscript>();
}
void Update()
{
//resets éverything so the car doesn't keep moving forward forever
moveSpeed = 0f;
steerSpeed = 0f;
moveAmount = 0f;
steerAmount = 0f;
//checks if the car is touching grass (variable localized from the collision script) and reduces car speed accordingly
if (collisionChecker.isTouchingGrass == true)
{
grassSpeedReductionMultiplier = 0.3f;
grassTurnReductionMultiplier = grassSpeedReductionMultiplier * 2f;
}
else
{
grassSpeedReductionMultiplier = 1f;
grassTurnReductionMultiplier = 1f;
}
if(Input.GetKey(KeyCode.W))
{
moveSpeed = 20.0f * grassSpeedReductionMultiplier;
}
if (Input.GetKey(KeyCode.S))
{
moveSpeed = -15.0f * grassSpeedReductionMultiplier;
}
if (Input.GetKey(KeyCode.A))
{
steerSpeed = 200.0f * grassTurnReductionMultiplier;
}
if (Input.GetKey(KeyCode.D))
{
steerSpeed = -200.0f * grassTurnReductionMultiplier;
}
steerAmount = steerSpeed * Time.deltaTime;
moveAmount = moveSpeed * Time.deltaTime;
transform.Rotate(0, 0, steerAmount);
transform.Translate(0, moveAmount, 0);
}
}
looks like this right now
MoveRotation is better ofc but yeah for rotation it wont going to make a huge deal
Force/Velocity is def what you want though if you want accurate physics detections
lmao why are the floats at the top formatted wrong... doesnt matter for now
normally large code we use code paste sites
So I just wouldn't have to make up for framrate differences at all?
yeeeah sorry
right its moving on a fixed timescale (physics) so deltaTime isnt needed
but ideally you move the linearVelocity part to FixedUpdate
the rest can stay
this doesn't really matter but just a tiny easy thing to learn, if you see repetitive code like this give it a look for a sec and think about how you can avoid it, here you don't need to * by your reduction in each if you just do it afterwards (since you do it in all those options) eg.
if(Input.GetKey(KeyCode.W))
{
moveSpeed = 20.0f;
}
if (Input.GetKey(KeyCode.S))
{
moveSpeed = -15.0f;
}
if (Input.GetKey(KeyCode.A))
{
steerSpeed = 200.0f;
}
if (Input.GetKey(KeyCode.D))
{
steerSpeed = -200.0f;
}
steerSpeed *= grassTurnReductionMultiplier;
true! thanks :)
https://pastebin.com/E6xErgkw making up for past mistakes
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.
Also no judgement, I'm only pointing this out because it will help you when asking for help and googling stuff, in your comments when you use the word localized your probably looking for the word referenced/references.
btw next time use the sites here 👇 pastebin is full of weird adware /scams
!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/
📃 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.
thx
im gonna be so real w/ u, i was SO sick of unity when I wrote those comments a few hours ago
i didnt even remember the word "reference" existed
ive usually used it before
Small question.. how do I make the movement consistent with the car's rotation? If I use linearvelocity, the vector stays the same regardless of the cars rotation
linearVelocity is using World coordinates by default.
you can use the forward of the object,
depending on where your forward is setup with the sprite, up (green) or right (red)
eg
direction = transform.right * speed
you need to switch the pivot to Local mode so you can see exactly
On that topic, do you know where solo devs can get help improving their code? I feel this isn't talked about that much
research online, specific questions here. if there's times where you are looking for just a general code review if you share stuff in a thread in code-general and make it easy to access and fairly focused people might spend some time checking it out
yeah green is down rn cuz the car is facing down
sounds dumb but just kinda comes down to figuring out what you specifically don't know and working from there
I'm saying the starting arrow, before hitting play
oh ok
so green is forward
indeed. thats transform.up
basically thats your local facing direction compare to world Vector2.up
mhm
i can see that
so i just plug that in
hold on
i might just have ot read the documentation again
yes the only difference why number worked different in Translate, because by default it moves in local mode to the object
thats what i like about it
and i reckon thats why my teacher recommended it as well
now that im getting deeper into this its kind of mid though
OH I GOT IT
learning about some basic vector math is important to gamedev
good thing its easy in unity
being able to just use/multiply the local transform cuts out a lot of the harder math
https://paste.ofcode.org/39ZUfFKzKwULbRHMEs9nmwz hello, when my player picks up an Object, I'm setting 2 bools to true, and then the player can eventually throw it back if he wants if the 2 bools are true, the throw works and sometimes it doesn't in build, so I've tried to find what the issue is in editor and one of the bool isn't getting set to true sometimes, why could this happen?
do you have a question?
ohh yea my bad, I forgot lol
how are we supposed to know a. which bool is the one not getting set back to true?
or false or whatever the issue was
you didnt provide much info apart from the code itself
the bool not getting set to true is the one from TalismanThrow
So send that script as well...
have you tried debugging to make sure it reaches that point? are you getting any errors?
is that boolean a property?
probably just something setting it to false right after, but it'd be nice to rule out other possibilities
no but the other bool is getting set to true so I thought there was no need to add any debugs, because that's literally the same
I checked, it's never getting set to true
but it's just a bool, not a function or whatever, could the issue come from the script itself?
if something is changing that bool yes....
is it only getting set to true in this script you sent?
bugs come from some assumption you've made being wrong. try to make as little assumptions as possible when debugging
it could be targeting different instances for all we know at this point
do the debugs so you can be sure
yes, because it could also be a function lol (property with setter)
well, I just checked the script and there is just a bool in it lol
no functions or whatever
we don't know that
just one line
is it a property or a field
field
and i assume it's public?
yes
is anything else assigning to that field
no..
why not just send the script...
and how are you verifying that
okay 1sec
also how are you verifying this?
Well, there is no code using this bool, and I've just watched when the player interacts with the Object
one script for one bool , that doesnt look right to me
how have you verified that there's no code using this bool
I've looked at all my scripts
have you tried a find in project or making this field private and see what errors come up
why? I didn't want to add this bool into my big GameManager because it'd be less organized and all the other scripts aren't always active, they are dynamic and this bool gotta be always active
in project
and you only ever set it to true?
yes
do you only have one instance?
yes
wait, by instance you mean only one variable with this name?
or like many scripts
instance of this component
only one
I think I'll firstly try to organize everything better, because that code has so many useless lines and debug everything
I would argue debugs are the least useless part of it
you mean they are important?
you could also use an event to set the other bool to true whenever you set the first bool true.
if done right they certainly arent useless
but that'd be the same as my current code no? setting a bool to true but it doesn't work for whatever reason
well you said only one of them works so no idea what you ment by that
tbh, I don't think it will help here in my case because all the other lines in the function are running but I'll still do it
yea exactly, only one works
have you just done simply
manager.hasTalisman = true;
+ Debug.Log($"before set, hasTalismanPrefab {Throw.hasTalismanPrefab}", this);
Throw.hasTalismanPrefab = true;
+ Debug.Log($"after set, hasTalismanPrefab {Throw.hasTalismanPrefab}", Throw);
interacted = true;
Is Throw an object in the scene or a prefab
You are possibly setting the bool on the prefab and so the one in your scene is unaffected
an object
I'm adding this, thank you so much
if it doesn't help, I'll just use only one bool, having 2 bools was kinda useless
I've found the problem @naive pawn @polar acorn @solar hill @frail hawk
I was setting the bool outside the Raycast if statement, so even if I didn't throw the Object, the bool was getting set to false
someone once said, never underestimate the power of debug.logs
lol fr
i don't mean to put you down or anything, but you did say previously that nothing else was assigning to it, so take this as a learning oppurtunity to validate assumptions i guess lol 😉
is there a way to set the current forward/backward velocity of my player object to 0 while leaving the velocity in other directions unchanged?
local space
as in transform.forward
yes, its an rb
im gonna get the code real quick
I need help with a bug with one shot audio. Whenever I reload the scene it constantly prints errors about the audio source being deleted. I tried calling donotdestroy when it starts, but the error still happens and it ends up breaking other logic.
(https://paste.ofcode.org/q6uSfJiqgajytJhGJDk7J5)
is there a way for me to make the code I send collapsable or smth btw I feel bad because of how large it is
transform the velocity into localspace, zero out the z value, transform it back, assign it back onto the rb
use a pastebin site
!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/
📃 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.
jeez that sounds complicated
are there terms there you don't know?
(i don't know how much you know, so if there's some part you're unsure of, say so and i'll grab resources or explain)
well i dont know how to transform it into local space nor how to transform it back or how to assign it back into the rb
what do you mean by "reload the scene" exactly?
loading in playmode, exiting playmode, opening the scene in edit mode, the button that says reload scene in editmode?
i do understand what you mean, though.
the last part is just, rb.linearVelocity = newValue
if you don't do that then nothing will change, since Vector3 is a value type
Transform provides functions for this
in particular you'll need these 2
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Transform.InverseTransformVector.html
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Transform.TransformVector.html
Whenever the player loses I have a button that loads the scene again.
you broke the link
no need to mask it, but fyi the mask format is [text](link)
I loooooooove unity documentation. thanks sm!!!!
thats mb I was having trouble pasting for some reason
does it work now?
yeah
oh yeah discord is a bit weird with pasting links. if you have text selected it turns into a masked link using your selection, instead of just replacing the selection. it's kinda jank, i don't really like it either...
is the object with BirdScript (i assume the player object?) marked DDOL, and is the AudioSource marked DDOL?
No, I tried marking audio source as DDOL but it was still printing errors and started breaking stuff,
I haven't marked the player object yet though, hold on
i'm not saying to do that, i'm asking for info about the current setup lol
so when you scene reload you do get a fresh player object and audiosource from the scene, yeah?
ah i see
you've leaked an event listener
you never unsubscribe to jump.action.started, so whenever that fires after reloading the scene, Jump on the now-destroyed player fires, trying to access the also-destroyed audioSource
since you subscribe in OnEnable, you should have unsubscribe in a matchingOnDisable
(and to be clear, assuming the player/audiosource are in the reloaded scene, you don't need either to be DDOL here)
Ohhh, that makes sense
I tried it and no errors are printing now, tysm for your help
i wanna change the volume override values from code, it works but doesnt reflect in the scene
Is the code running
...so it doesn't work then?
what's working and what's not working, exactly
the code runs cause when i select the volume profile i can see the values changed, but they dont reflect in the scene
and yes its the profile used by the urp asset
ohhh i was thinking audio volume lmao
Might need that always refresh thing ticked on top right of scene view?
it was the first i checked but no
Psycho solution but does turning the component off and on via code when you change the values help?
not the component but it works if i turn off and on the override
Close enough
maybe i should use the override function instead of changin the value directly
yk what this really isnt #💻┃code-beginner level lol, ill make a thread
hey guys, i really wanna get into coding but dont know shit, can anyone teach me?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
there are also c# courses pinned in this channel
Is it normal for learning C# to get more depressing as it goes on. I originally felt comfortable up to like a mid-intermediate section. But things keep advancing and getting more and more confusing and its starting to make me heavily procrastinate studies
no, that sounds like burnout
Because i know next lecture session is going to be a bunch of convoluted BS that i will only partially understand
sounds like it's going at a pace faster than you're comfortable with, i guess?
Then you are probably missing something earlier on
I'd seek for fundamental programming courses like cs50 (heavily recommend, it's free), before tackling more "specialized" courses for c# or Unity.
perhaps try reading in your own time, see if a different resource can help it click
Should i finish a course first through advanced, and then read and practice or just what..
or if there's a specific concept you're stuck on, feel free to ask (though, if it's just general c# it may fit better in the c# server)
if you're not going to understand the next lesson, then the ones after that you won't understand either. no benefit in powering through, something's gotta change
im aware, but im way better 1 on 1
I didnt skip any sections so not sure what i would be missing. It just feels like teachers start skipping over details as if sections would take too long if they explained everything
go back to the first one where you feel your understanding is incomplete. research so you understand more. go from there
So go back and review. You can check up on things you didn't understand
You don't have to be told by a teacher
learning isn't a QTE or a limited time event
Well not really. Its more like swiss cheese. In late intermediate classes Ill understand some concepts and then but totally confused on others
Like some C# sections were designed poorly by microsoft
cool, then go learn more about those concepts
(without more specific questions we can only really give generic advice)
So go back to the ones where you haven't gotten everything, and review it. Find the things that you didn't understand and research them
I don't wanna push this course too much, but I'd say the cs50 lectures and problem sets are pretty darn effective at teaching programming fundamentals, I'd say it'll help you specially if you prefer 1 to 1 explanations. Give it a go
I know this is a fallacy because programmer "language" and language language is different. But i found immersing myself in russian/etc was much more beneficial even if i didnt understand what was going on in the grammar etc. I was just wondering if it might be beneficial with C# even though the logic is different. I just wasnt sure
You're not going to get 1-on-1 tutoring without paying up
thanks for the help. i will consider reaching out
Not qualify tutoring, at least
Okay i meant qual ity, but it gets censored for some reason?
i think the resemblance is closer than you think
if you just read a lot of c#, you'll probably be able to understand the gist of c# even without fully understanding the logic
the difference is in writing. with human languages, the other person can fill in the blanks when your grammar is off. a computer can't do that, it has a set of expectations.
quality?
read the automod message. edit message exists
why would quality be censored 🧐
Same question here, maybe it was because i added a *
Ooh, my bad, "please complete sentences with full context"
The bot doesn't like doing the "one word*" replies because people keep using it instead of just editing the post
yeah you cant just do "..." or something like that
You can just press up arrow and edit your last message if you make a typo
Hi
so if i understood things correctly, the way lists work u can quickly look up a value based on index, but you need to loop through the whole list and check each value to be able to get the index of a certain value (if it exists in the list). is there a list-like data type that has a quick look up where u can find both the index based on a value u have and the value you want based on the index you have
IndexOf you don't need to loop
Are you more concerned about performance or ease of access?
performance
actually also currently i have a list of vector2 so maybe indexOf might not work cuz of float point imprecision?
vector2 has approximate for == / Equals
What task in particular are you using the list to accomplish?
cant you just use dictionary or hashset ?
i thought about dictionary but i was unsure if it does work that way, like a fast look up in either direction
dictionary doesnt have indexes though
Why not both?
i thought it worked just like a list but except of having just int index you can index things with differentdata types
make the value an int could mimic indexes thpough right
yea i realized maybe just making two lists would solve this but i was just curios if there was a better way
you could do that too, not sure if its optimal
An index is an offset from the array/list start which is why access by index is fast
its literally "pointer to array + (type size * index)"
In simple terms, quick maths
at some point the dictionary does lookup faster too iirc
i just dont know how i could use indexof with float imprecision, i dont see how u can use vector2 approximate without a loop
oop didnt mean to reply
when the size gets large you mean?
Well index of is just looping till it finds a comparison match
You are right though, float and double are not reliable or this or for being used as keys in a dictionary
I think indexOf still uses loop in backend. anyway
It does, no magic
oh true even dictionaries wont work for the same reason
Dictionary uses hashes and bags to do faster lookups compared to just looping over everything
So the answer is use a type that can be reliable as a "unique id"
huh
== does approximation for floats but Equals doesn't
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Vector2.Equals.html
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Vector2-operator_eq.html
If the object knows where it's at on the grid (x,y), you can use a dictionary to lookup its own position quickly; given the object.
At the same time, you could use a multidimensional array or list to manage the object relative to its grid position.
You'd simply need to update both its grid position and stored position when making changes to position. This is more for ease of access as using more collection does include additional expenses in memory allocation. Actual performance in speed would vary but should correlate with the respected collections.
You're better off using what you're comfortable with.
but yeah dont use floats as keys lol
Im a int index = x + y * height; guy
but dictionary would mean we are using vector2 as key and that would lead to floati mprecision, no?
also its not a grid based system, sort of, its based on world position, to do it grid based would require me to rewrite a bunch of my current system, which hey, if its better ist better, might as well get to work, i mean the pathfinder does use a unity tile map as its like base when searching/placing nodes, so could js use that, but during pathfinding we constantly recalculate the path, distance calculations, moving targets, we would then be doing a lot of CellToWorld() calls, i think have an effecient way to just do a reverse lookup might be the best way, maybe since its grind based i should move the tile maps up and right by 0.5 tiles, and make the list a vector2int, that way the center of the tile always lands at number that doesnt require floats
althought actually i do node placements at half tiles too so floats will still be needed
maybe storing the number *10 then diving by 10, avoids floats then?
which would allow using the disctionary concept from before
For grids we can use Vector2Int as the key
previous comments about float/double still stand
some tile maps will have a lot of nodes also so if its true that disctionaries are more effecient than lists at larger sizes would be one more reason to use em
but its not strictly one node per tile, there could be one at 0,0; and one at 1, 0; but also one at 0.5, 0
Then you either have a denser grid or group objects using kd trees
You could also try using reduced precision positions stored as int or long or even a custom struct with your own stable hash code
But these are not very beginner friendly
You could also try using reduced precision positions stored as int or long
by this you mean like multiplying by 2 to get rid of the .5 to be able to usevector2int?
something like Mathf.RoundToInt(x * 100)
is there a help channel
basically every channel is so ask away or check #🔎┃find-a-channel
There's no command called
vsc.
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
& did you check the console tab in unity for errors ?
hmmm.. you never call ProcessInputs anywhere...
I know the solution to this is probably long, so if someone could just point me in the right direction i'd appreciate it: I'm trying to make it so two gameobjects get a random material selected on keypress, and I want to make sure they don't both get the same color. I'm new to coding and am having a very hard time figuring out what i'm doing wrong. Where specifically can I look to help myself understand what i'm doing wrong in this part of my script?
public Material[] PossibleColors;
//private Renderer ColorRenderer;
[SerializeField] public GameObject LeftCube;
[SerializeField] public GameObject RightCube;
private void Start()
{
if (LeftCube != null && PossibleColors != null)
{
Renderer LeftColorRenderer = LeftCube.GetComponent<Renderer>();
if (LeftColorRenderer != null)
{
int LeftRandomColor = Random.Range(0, PossibleColors.Length);
PossibleColors.material = PossibleColors[LeftRandomColor];
}
}
}
Ok, so what is happening that is not supposed to?
Well nothing at all is happening at the moment lol my code is totally broken and i'm trying to figure out what I need to learn to achieve my goal
yeah doing .material on that array makes no sense
focus on the random material selection. do you know how to get a random value from a collection (list, etc.)?
you can make it simple enough where you toss what you have in array into a temporary list then just remove the item you already chosen for object 1, if you random rangethe list again you guaranteed not to grab an already chosen color
If i'm understanding this correctly, I think so. I have a Material[] array and am later calling it using Random.Range(0, X.Length)
Does that mean there's a way to 'shuffle' the already defined array I have in the game editor?
well, you're not calling it, but using its Length property. what does Random.Range do?
you can do .ToList() and move it to a temporary list, the difference is you can remove items from a list unlike array.
You can still do it simply with array but have to work with a loop
It selects a random value from an array starting at the first 'slot', in this case '0'. Right?
also you should configure your IDE if this is not underlining red
PossibleColors.material = PossibleColors[LeftRandomColor];
array has no such property .material
put the result directly into your object1 or a variable
Okay i'm going to try toying with that a little bit with a new script to see if I can get the jist of it. Google gemini is giving me some good solutions but it just feels like i'm copying and pasting rather than being given actual explanations
yep, nice. it returns a value (the index) from the array. this is great when using it once, but your worry is that, using it a second time can result in returning the same number . . .
yes because learning this way won't benefit you much at this stage . You need a bit more basics in c# tbh
@gilded harbor to avoid returning the same number, you can implement different tactics. i would think of how to check or avoid getting the same number . . .
nav mentioned copying the array to a list, then using the copied list and removing the first index returned (from the list). this avoids selecting the same index again as it is no longer in the list . . .
I'd recommend to brush back up on c# basics like array, lists, loops etc
but yeah cause as mentioned, there are different ways to solve this (like anything in dev :P)
if you want to avoid creating a copied list, you could simply check if the second returned index is the same as the first, then offset by +/- 1 to return a different value (index) . . .
Yeah I have this book i try to reference a lot but it's not fully committed to memory. So, ToList, IndexOf(), Contains() might also be good places to brush up on? This book I have isn't specific to unity but it is c#
the Unity bits come after, yeah just normal basic c#
unity just has some concepts about the engine like GameObject or Inspector / components
but none of those change anything about how c# works . So you're just essentially dealing with an API code wise
Okay gotcha. Thanks so much, this channel is always so helpful. Every time I think i'm starting to be more fluent in this I get hit with a new challenge and this is always the best resource.
I'll definitely do a little more digging in this book in those areas
this channel has good resources pinned if you prefer interactive or tutorials on these
The biggest problem underlying every roadblock I hit is not knowing where to even look, being pointed in the right direction is super helpful. i'm starting to understand what people are talking about when they say tutorial hell
unity is just an API; most of the challenges come from solving problems, like, how to connect one thing to another, how object A affects object B, etc . . .
every concept, idea, problem, mechanic, or system is just a series of events (steps). these are many tasks, like on a to-do list
break it down into parts, then those parts into pieces, and you'll have a list of each individual task to complete the entire concept
those individual tasks are what you can search to help find answers . . .
I definitely will keep doing that. Thank you again for helping point me in the right direction for getting over this hurdle 🙂
if I am trying to create a basic first person 3d projects, what are some useful websites or resources i can use other than videos/tutorials? in the past i’ve done some basic games, but I want to truly understand everything from the ground up.
-# btw I can’t always respond, so to anyone replying, if you don’t mind pinging me, that way i can keep track of the message
there's a lot of stuff you could go into, so it depends on what you're interested in
there was a website about vector math and such with diagrams but i can't seem to find it...
oh damn i found it
a bit less complete than i remember though. so ig nvm
When attaching debugger to unity it asks about session and recompiles which takes a long time with burst especially. Is there way to make that iteration speed faster?
Heyo, i’m currently working on my first real game and give myself new challenges. I want to have some sort of base from which i can start missions etc. Simular to games like darkest dungeon or hades etc.
Since i never worked with data between scenes i do not really have an idea where to start or what is the term/technology i need to look into. So whats the term/technology behind such logic? Is is persistent data?
DontDestroyOnLoad & Additive Scene Loading are terms you can look into
i fixed it, but no idea why it gave me error. ```
if (!Directory.Exists(SavePath))
{
File.Create(SavePath);
return;
}
last thing to fix is id not saving in scriptableObject, it resets with new session.
What you mean by reset with new session? does it generate a new ID everytime?
if i reset my unity. cant test with build right now, gave me 6 errors.
So entering playmode also gives you 6 errors? Or not even entering playmode?
build, but its nothing to do with id
I mean thats what your code does, id is not serialized
idPreview is, is that saving?
idPreview is for previewing id, it doesnt change id
ok
but like
idPreview is the only thing there that can be saved
(you can probably fix and simplify this just by adding [field: SerializeField] to id which will save id and show it in inspector)
private setter on your id will not serialize and therefore reset everytime
[SerializeField] private int id;
public int ID => id;
Something like that should work
you can also use , HideInInspector behind your serializefield to not show it but still have an accessable public value "ID"
You can just add the field SerializedField directly to the property
Appreciated
you can have properties with private setters with their backing fields serialized
unity doesn't use the setter
it uses reflection to get the backing field directly (since SerializedField needs to be applied to the field)
So without the SerializeField property, Unity will not serialize it, right? Or am I mixing things up here, how unity and "native" c# handling things
unity serializes fields with SerializeField and public fields
public int x { get; private set; } is neither
[field: SerializeField] public int x { get; private set; } is the former
to be pedantic, SerializeField is an attribute. "property" is a specific term in c# so the distinction is important.
ah my bad, yeh, attribute, absolutely right. so the attribute should fix swortechs issue in this case.
Yeah, with the additional field: part so it correctly serialises the backing field
guys how to get a direction to Torque the rigidbody, between 2 rotations, current one and desired one, just like with position doing target.position - transform.position, how to do the same but with quaternions???
Quaternion.Inverse is probably helpful here
For getting a difference between quaternions
Though it's probably easier to calculate the angle difference per each axis (X, Y, Z) with Vector3.SignedAngle and use those for your torque force vector
Any idea what it is this time? Again 0 changes but it seems the line endings are the same this time as well - also isn't allowing me to undo the "change" (it doesn't disappear)
might just be different encoding
Sometimes got does this but when I stage such a change/file it realises and goes away
You can always discard the changes/reset it
Sometimes git does this. See if the change goes away if staged (I see this a lot myself)
Ah yeah staging made it disappear
Thanks a lot!
idk, if my issue is for coding or input system. i have singleton which has ActionReference ```void OnEnable()
{
BackInput.action.Enable();
BackInput.action.performed += Back;
}
void Back(InputAction.CallbackContext context)
{
switch(CurrentState)
{
case GameState.Playing:
Session.Dispose();
SetState(GameState.LevelSelect);
break;
case GameState.LevelSelect:
SetState(GameState.MainMenu);
break;
case GameState.MainMenu:
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
break;
}
}
void OnDestroy()
{
BackInput.action.performed -= Back;
BackInput.action.Disable();
}```, but i have issue after switching from [Playing] to [Levelselect], action doesnt work. Maybe, PlayerInput change something in [Playing] state scene
Did you log your code, so you know, what state updates you get?
yes its in SetState. debuggin old and new state.
But not in your back method for example.
state isnt issue. back isnt called after finnishing playing
debugged more and PlayerInput disables it
doesnt matter where i try to enable action, it only can be enabled in update().
try to comment out your timeScale
what is it to do with input action?
time scale only affects physics
timescale affects anything that uses deltaTime or fixedDeltaTime
if you have hold inputs set to scaled time (if that's a thing) they'd be affected - but it shouldn't have an effect on input actions as a whole
but in my instance it doesnt effect input
Okay, it was just a test, because it CAN affect it. So as you disable the input system on your gameobject, I guess, you are not using a DDOL pattern for the input script you pasted, right?
GameManager is DDOL
So is this code on gamemanager?
i dont know who disables my action
yes, because im lazy. you can call it StateManager
thanks Osmal for ruining my free day
So if you remove the OnDestroy and OnEnable part entirely and just enable it on awake or start, does it work then?
why are you using OnEnable and then OnDestroy? sounds like that could leak listeners
you generally should use symmetric messages, so OnEnable/OnDisable, or Awake/OnDestroy
because VScode and unity gives warnings.
What warnings?
i shouldnt use disable, but destroy
never read that ever in unity OR vscode
what's saying that
can we stay on topic
this is on topic
playerInput class disables my action
having improper messages can contribute to various issues
So if I get you right, you are a) enabling your actions through code but also use the playerinput script, which will enable its own assigned actions too.
Player uses playerInput, but gameManger needs action to call back. maybe, i should make unified inputmanager
so you could either use the playerinput and register your gamemanager classes to it or as you said, combine your inputs into one thing, so you do not run into multiple handlers for the input system
maybe i could do it, i have reference of player. maybe, can get playerinput and assign it
But its a bit hacky, as you always gotta be sure, that you are not assigning something to the playerinput, which as been already assigned and what not or run into null references, because you lose the connection to the event
or i can call from player gamemanager instance and switch state
it wont work
I guess your playerinput sits on a player prefab that gets created and removed?
yes, my game isnt in 1scene
Are your playerinput and your gamemanager share the same action input class?
im using unity playerinput
As far as I remember, the playerinput class holds a reference to the action input, right?
yeah
So my guess is, that the playerinput , whenever it loads, creates a new version of your input class and therefore you lose your gamemanager one. So you could also just use a second input action set for the player and one for the entire game.
but it works, while playerinput exist
my computer shut off while i was away and im unsure if i had unsaved code or not, does any1 know what the blue lines on the sides mean, or the little red traingles, or why in the explorer there are ⛔ typa signs?
are you using version control, like, git?
yes first time using it
unsaved changes in VS are yellow lines
VS doesn't do auto saves, if VS closed and you had unsaved changes.. they have been lost. It does not matter if you have version control, it makes no difference in this situation.
a quick google search gave me this : https://stackoverflow.com/questions/44129996/blue-lines-in-visual-studio-editor-margin
they're version control change indicators, both in the gutter and in the left side of the scrollbar
the red triangles are deleted lines, green are added lines, blue are modified lines. try clicking them, they should show what changed
this seems like a different thing
how so?
those are file changes, these are version control changes
the styling is different, they seem to be a separate set of features
styling is because it's for an older version.
it's also saying the blue is supposed to be reverted changes but that certainly doesn't make sense in this screenshot, and it makes no mention of the red triangles
because the question on the post didn't ask about red triangles 😄
my point is, all 3 of those indicators are part of a feature set separate from the one you linked
the same presentation is used in vscode for source control features, for example
I don't really care though, I did a 2 sec google .. they seem close enough to me, but couldn't care less to find out further.
so why are you arguing against me then lmao
A dicussion != argument lolollololollol l 😄
i agree, but you have not been discussing, only deflecting.
fs chris.
seriously though.. you say you googled it for 2 seconds, found something "close enough", and when disputed you deny every point i make
knowing this is pretty useful info actually, it's helped my workflow quite a bit, so hopefully you learned something
the ⛔ signs look like they're toggleable, are they? if so then it's probably excluding stuff from the search
hey guys why th is this not working
it doesn't indentify actions
make sure you don't have a type of your own called PlayerInput
wdym
i mean what i said
if you have a type named PlayerInput in the same namespace, you'll be referencing that instead of the inputsystem one
try hovering over PlayerInput and see what namespace it says it's from
bro dont abondon moi
..i gave you instructions on what to do
if there's part of that you don't understand, say so
i can't read your mind - if you ask for clarification on a certain part i'm happy to oblige
Sometimes really the strangest interactions happen on here xD
So did you just not read their answers or do you just not care
what
You completely ignored their messages that tried to help you
oh this
You were given a very clear answer, an explanation on how to do it, and even something to check to get that information and you've just ignored it
i didn't understand and said wdym and i got impatient so i said bro don't abandon me so ye
not clickable nope
not sure what it is then
you said wdym, i explained.
what were you waiting for
wait what
They literally replied to that with information on how to check how is that abandoning
ok im sorry
can you show me pls where
If you want help you should actually read the replies you get
I don't know what else you could want
go back read
uh is it this?
and the one i directly linked to you, yes #💻┃code-beginner message
Hello , i'm planning to make an equivalent to mario kart "ghost" but in a 2D platformer (meat boy style) ,basically when you finish a level , if you retry it , a ghost who copy the movement you had done will appear , do you have an online tutorial who show how to do it ?
ik
so like
can you clarify what you mean now plssss
do you just not understand a single word of what i said
if there's part of that you don't understand, say so
i can't read your mind - if you ask for clarification on a certain part i'm happy to oblige
do you know what hovering is?
you could probably google for this kind of stuff, ghosts in 2d platformers aren't a foreign concept so there would probably be tutorials for that
i asked here because i did not found anything on google 😕
can you tell me wdym by "make sure you don't have a type of your own called PlayerInput" pls
i hope im clearer
2 of the results here are for what you're asking and they provide keywords that you could use to search for others
in fact with the extra replay keyword, there's one using super meat boy as the example
ok thanks you , i guess i did not use the good keywords
googling effectively is a skill too, you'll get better with experience 😉
I've been scratching my head for a while for this... how do you assign a Slider with code?
I was trying something like this
that should work assuming the objects are set up correctly, but why not just use serialized references
ok uh is there something called hovering on discord
cuz im genuinely confused, and i think im an idiot
you just sent me a #somethingidk which im pretty sure is the thing im asking about, so ig there is something im not gettinggggg
hovering is when you put your mouse over something
these blue things are links.. click them..
so there isn't something called hovering on discord
hovering is a computer term
ik you just showed me the same thing i need clarification for???
do this, make sure it says UnityEngine.InputSystem.PlayerInput
no, those were the clarification
those were literally AFTER you asked for clarification
ok so can you clarify the clarification
this person is either a troll. or simply incapable of the level of computer skill required to work in Unity.
cuz i dont understand
Do what the video is showing you to do.
If you continue to act this way, then make a thread at the very least so you're not flooding this channel with more noise.
Why would you assume it's discord related when you asked a question about code and got an answer about code
ok
but i was asking what he meant
i dont get why i keep getting this error though. Also what do you mean by serialized references? not familiar with that yet
or she
you probably imported the wrong Slider then
try hovering over Slider and make sure it's the one from UnityEngine.UI (i think, something like that)
They meant to do what you see in the video. Make a thread, you're making noise at this point if you can't follow basic instructions.
ok
just making sure, it wouldn't be a disturbance if i made one here right? or should i put it somewhere else
Heres' fine
serialized references are when you drag stuff into fields in the inspector. they're generally much easier and safer than using Find
like right now, you have expSlider as a serialized field (because it's public, one of 2 ways to have it be serialized)
if you drag an object into that slot in the inspector, that'd be a serialized reference (and you wouldn't need to do expSlider = ... in code)
what i'm recommending is basically that, but instead of GameObject, you would have Slider instead, so you wouldn't need the later GetComponent either - you would have direct access to the slider
ah just noticed you have the imports in this screenshot. yeah looks like you're using UnityEngine.UIElements.Slider, which is for uitk - you probably want UnityEngine.UI.Slider, which is for ugui
I have roughly 200 objects in the ceiling of an environment with more being added throughout run time, and I have a vehicle that we drive around in the environment. I need to know if there is ever a time when there are none of those objects above the vehicle. Would it be more efficient to add trigger colliders to each of those objects and a bounding box above the vehicle that does uses a Physics.OverlapBox to check the layer the objects are on to see if any are within the box, or would it be better to add bounding boxes to sections of the objects, using the encapsulate function to grow the boxes around any newly added objects, then do a check if we are within any of those boxes. There are about 20 of the boxes, for reference.
is it 20 boxes total that you're checking, or the 200 objects? i'm a little confused
20 boxes. Each box has a group of the objects. But if we did it with just one box over the vehicle, we would just use the Physic.Overlapbox to check the objects directly.
so your question is between 20 boxes or 200 objects?
those are both pretty small numbers. you should focus on a working and maintainable solution first, and then worry about perf if there are perf issues
.actions problem in c#
i think a boxcast or indeed overlapbox against the individual objects would be sufficient as a starting point, then go to more complex optimizations only if necessary
OH! That worked? what is the difference between UI and UIElements and when can i use one or the other?
as mentioned before, the separate namespaces are for separate.. systems? libraries? i'm not quite sure what to call them
UnityEngine.UI is the one for the default ui canvas, buttons, sliders, etc
i don't really know anything about uitk other than "it exists" so i can't describe that one to you
ugui is unity gui, uitk is ui toolkit, in case that helps with further research
I am doing find because that is what I am familiar with and this object is instantiated (so can't drag it to the field) so it tries to find the slider to be associated with it. I am still looking for better ways to implement this though
ime there's always a better way to get direct references than with Find, but i'd require more context to determine how for your case
Find is ultimately based on magic strings that you write yourself so it's always one of the worst options in a given scenario imo
(if you have other stuff to worry about for the time being i'd understand, no pressure to change right away, but i encourage changing eventually)
yea I did hear that before about using find as not very efficient. I will have to research on better ways when optimizing
So Im trying out the visual scripting, and I have made a simple script, but I dont know how to put said script on an object. How would I do that?
if you google visual scripting tutorials they should tell you? if you're having issues with it i guess ask in #1390346878394040320. most people here won't know, as this channel is primarily for the c# scripting.
alr thanks
Why does it say RandomRangeInt cnt be used from a monobehavior construction what does that mean
also using UnityEngine.Random doesnt exist in vscode for some reason
Someone help with this please
could you show the actual error? info is lost when you paraphrase errors
RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer)
You can't call functions in field initializers. You have to set the value in Awake
specifically you can't call instance methods of the current class
what are you trying to do?
Ok how do i just choose between two numners 1 and 2 when the game starts
Then do it in start
I've coded so when a collision happens, it adds a force in a direction. How do I make that the opposite direction of the collision?
you can get a contact normal
woops
So uh up till now i did OnTriggerEnter2D(Collider2D collision){BoundaryHit = True} to stop the object from mvoing any further and now ive went and did ther shit and suddenly it just doesnt work anymore
I how do i use it here? Do i make the force -other.contacts[0].normal?
How do i make it so an object with a rigidbody2d not get flung away by another thing
Does this need a rigidbody? When i used a rigidbody2d again it works now i really need help
make it kinematic or have a lot of mass
If you want it to stop moving on contact, why is it a trigger? Why not just use a solid collider
hey i wann add animation to my script but im unsure where to put it and when i go on a youtube vid it doesnt work it gives error codes
i can move normaly but i want to do a animation for example moving right and left and up and down
you don't animate a script 😛
the script just controls the animation
use something like a Blend tree
ya but i gotta add stuff
"stuff"
You meerly control the parameters
Ok so you already have the blend tree then you need to control the parameters only through script.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
whats this
so i post my code in there
You post it with one of the links provided yes
i got it in one how i send it to you
save and it should generate the link, send the link in chat
there should be a save button somewhere
or just try paste.mod.gg
a powerful website for storing and sharing text and code snippets. completely free and open source.
got that one working
Your current script is Missing reference to the animator you want to control
and linking Inputs to the "inputX/inputY" parameters.
so what do i add
the things I just mentioned lol
start with the basic , do you know how to add reference to the Animator ?
could u please explain what you mean refrence
thats what it shows on unity
sorry if i sounding dumb or so
when you want to do something with an object, you add a reference to it
how did you add rigidbody to control its velocity
Choose the best way to reference other variables.
look at the documentation as well, it also explains this simple process specific to Animator (don't randomly copy and paste)
https://docs.unity3d.com/6000.3/Documentation/Manual/AnimationParameters.html
i was watching a tutorial but when i do the animation part other videos have different codes thats why im confused
so you saying u want me to make a component aka the animator
if you look at different videos ofc they will have different ways to do it, there isn't 1 way to solve something but overall controlling a blendtree/animator parameters is the same
You don't Make the component, the component is already there to be used. You just have to reference it and access the properties etc.
scripts on gameobjects ARE components
Well, considering nothing in your code has anything to do with animation, and the videos you're talking about presumably do, maybe you should add it
you're skipping through a lot of the basics tbh you should start simpler
eh not really interested in the videos cause I already sent an example from the docs on how you control parameters through code
you just have to study it a bit
right. and those are Parameters as per link I sent
yes
you Control those through code
did you click the link I sent at all ?
this one
thats to learn about referencing
I;m talking about the Animation Parameters one, the documentation
im currently reading that one right now
it pretty much explains how the process works and has example code
don't just copy and paste the code, see how those relate to what you have so far and you mash those in
nah its fine no worry
just make sure you read it
i will just sometimes confuses me with different codes lol
yes it happens if you're skipping through many things to get here.
doesn't hurt to brushen up on basics first before taking such tasks
tutorials can be okay to show the process but its better if you understand why and how certain code is used
Okay I learned all movement and that it was just confusing how to add the animation to the same script lol
Because you can make a script all organised can’t you
In the different sections or so
I mean you can, but in the beginning doesnt have to be.
Ok
you can put comments or regions
As I’m making a table top game
start with commenting code so you know why that line is there
Okay
not to be pedantic, but remember the Script just Controls a component that controls animation
you add don't animation to the script itself, not in this context at least.
Ok so the stuff I did in the blend tree once I add the code for that it will use the animator to animate right?
yes Animator is controlling all the animating.
Blend tree just makes it easy to control multiple animation states/transitions with "centralized" node
Ahhhh that makes a bit more sense
Just reading this doc you sent then I’ll try and do the code part and that
And I can ask you if I need extra help
If that’s okay?
sure you can post here any further questions you have
I'll most likely be here or someone else will answer anyway
Ya I will do I will do it slowly so I can understand stuff better
Thank you again for the patience you have with me
But then my object gets flung cuz of reacting with the other thing
if its a boundary only there to stop objects why not just a collider, why a rigidbody on it at all ?
@marble hemlock there's many ways but that is one of them yeah
save stuff is a deep rabbit hole so there's always going to be a "better" way
at the very least maybe just for kinda general vibes maybe store it in a scriptableobject that is referenced by a singleton?
in general good to have data on so's vs. monobehaviours
mmm i will try that
it'll unfortunately have to be in like 4 days because im going to be away from the desktop but the idea has been plaguing me since yesterday
just been writing down ahead of time what i would put on it, since i'd then after sort of model the other scripts based on that "masterscript" thats tracking the overall progress of the entire game
going to continue writing for now though
wut
i wanna put the end on it
If you mean whats underlining red is nothing to do with closing }
SetBool has two params and InputAction is a class you need from the Input namespace
these are the current errors im getting
always start with the top error first
the first two should be able to correct the rest
missing two brackets at the end
says no overload for method setbool takes 1 arguments
Or they're just not in the screenshot
how to get the brackets at the end
oh
right, means there is no method SetBool that takes 1 arguement
does this not indicate that's the last line?
So, check the documentation for setBool to see how many arguments it does take
you add them...
and and yes the brackets at the end
is their a keybind or so that adds them
Yes. The } key
homie just add them
poorly pasted code you don't understand :\
oh and that moveInput - context.ReadValue is wrong
thats probably meant to be assignment
Okay, now you can start with the top error and work down
ok
you're literally using SetBool correctly the second time but not the first time , you can just compare the two and its obvious whats wrong
is the line 29 wrong setbool
considering its underlined red, yes..
tbh the longer I look at this code the worse it gets
would it be getbool then
why would it be GetBool
where did you get this code
What are you trying to do on that line
are you trying to Read the value or Assign it
In words, not code
Hmm it's using both input systems at once as well
so basically i want it so i can animate walking left right back and forwards and when not moving it goes into a idle animation
line 29 doesn't have any purpose on this if you're gonna do everything in the Move method anyway
so should i remove the line 29
But that line in particular
What is that line supposed to do
Individual lines have meaning, you know
tell it im walking
you're mixing two inputs systems and its gonna be more confusing
okay
Okay, does that sound like "Getting" a value, or "Setting" one?
setting one
to be fair, it could be either :p
oh, no, it's definitely just setting here
i misunderstood!
So would it be set then
seems you're trying to do the same thing in different places in multiple ways
so what would u do to fix it
pick one way to do it
could u explain what you mean
the move method you have there, from the new input system. You are already setting the bool in animator to true or false depending on inputs
assuming you correctly run that method
but i was trying to say when i start walking my animation starts and if i stop walking then i go into idle mode
so do you have it set in animator that way where "isWalking" controls if walking or idle depending on true/false
right so what do you think based on what I asked, do you think you have it correct?
i think i dont have it correct
maybe the isWalking is getting confused and doesnt know if its true or false
huh ? . forget the code right now.. do you think the transitions are set correct with the parameter isWalking
maybe yes
ok so yes?
so now what would you want in the code to say "Hey I'm moving, isWalking in animator should be true"
hey, i want my sphere to roll when you look downwards and i don't know how to do it with Vector3. can anyone help?
here's the mousemovement script
using UnityEngine;
public class MouseMovement : MonoBehaviour
{
public float mouseSensivity = 100f;
float xRotation = 0f;
float yRotation = 0f;
//public float topClamp = -90f;
//public float bottomClamp = 90f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensivity * Time.deltaTime;
xRotation -= mouseY;
//xRotation = Mathf.Clamp(xRotation, topClamp, bottomClamp);
yRotation += mouseX;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}
}
so maybe it should be false
wat?
so it needs to be true
you probably want some sort of angle to check if you're "looking down"
also you should not multiply mouse inputs by deltaTime they are already frame independent
so would line 29 need the true part then
don't be randomly guessing
im sorry
how do you want to tell the Animator you are indeed walking, what condition would set it true for example..