#💻┃code-beginner
1 messages · Page 255 of 1
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im in the code-beginner channel for a reason though. and I know the basics of programming :/
alrighty i will try to
This channel is for beginner unity help, not beginner c# help
they are basically one in the same
No
I've seen you trying to declare a variable in the method parameters👀
because you were suggesting something that confused me, and it looked strange to me too, but I figured if that was the right thing to do then I had more to learn
and I was asking for feedback cus it looked odd to me
and help on how to apply the logic correctly
instead I get told to go learn the basics, when im in a beginner channel
If you knew the basics, you'd k ow that it's an invalid syntax. You'd also know what they actually meant.
oh yeah, i meant c# specifically (idk if its good asking that in an unity server tho)
C# manual
I like the codecademy beginner one personally but really any work
Very interactive
I figured it was invalid, but went with it anyway trusting their advice, but applying it incorrectly. and no, I dont know what they meant, cus they werent really being clear enough for me
dont i need to instal smth so i can write the code and display the results? (like a console or smth)
Also just google. There are tons of materials online. !learn also covers some C# in unity context.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also, this channel is for c# on top of unity, cus its in a scripting sub-category. plus says CODE-beginner
Visual studio
download more ram
If you’re going to implement a solution, make sure you actually understand what it does instead of just copying and pasting
wasnt ram in-real-time computer capacity to have things open?
anyways, I am sorry for taking my frustration out on yall, im just tired of being told to "google it", "go to basics", and "read the documentation" when I am asking about a simple problem in a beginner-oriented channel. I am well aware that I need to learn stuff, but I am trying to find a solution to a problem
Random Access Memory, yes its whats being stored in realtime
and why do i need to instal more? ( also, isnt that impossible?)
Okay, but again, blindly implementing a solution without understanding what it does doesn’t really accomplish anything
And if you’re told to google it, then it’s a very googleable problem
it solves my problem and teaches me something along the way
we did give you simple solutions but if you cannot understand the suggestions, its best you learn those basics
Copying and pasting teaches you nothing
copying and pasting without taking the time to look at what you are copying/pasting, yes. but thats not what I am doing
I tried the solutions and they didnt work
looking and understanding are two different concepts
in order to understand, you have to look
tell me how a debug log I wrote "Doesn't work"
also, navarone, do you want to see on what i spended like 11 hours yesterday?
cause that would be amazing
oh the debug code im sure worked, but it didnt activate, which means theres something else going on
where did you put it then ?
so how do I fix the trigger
There could be many issues with your trigger
Show it in the inspector is a good first step
go through this
https://unity.huh.how/physics-messages/3d-physics-messages
its a very simple click guide make sure u follow through it
the first image is where the script is applied, the second image shows where the trigger is. its a child of defaultcube, which is what the building is determined to be
none of which have a trigger collider
oh wait nvm second one but you're missing the Rigidbody
I cant have the defaultcube have a rigidbody, cus then the swinging stops working
idk, cus the swinging mechanic isnt mine, i just know I tried the rigidbody earlier and it didnt work
as in, you cant grapple onto the building
this is why people say "Debug it"
"Idk" is pretty much not gonna get you far
you have to find out
idk what causes things to not work with rigidbodies, though
we can't mind read the entire project and its code, learning to debug should be your first step before even learning code
we can't know what you did exactly 🤷♂️ its all speculation
anyway using triggers isn't the only way, more methods exists that dont rely on Rigidbody
like Overlaps and such, but those require a lil more work to implement compared to OnTrigger
Yoinking other peoples code as a beginner can get really confusing when you implement your own features
A good first step could be understanding how this swinging mechanic works
its like stealing a car without knowing how to drive
But, once you become a more experienced coder, you can steal enough cars to cause a global transportation crisis
Gone in 60 Secs
im here, I was doing something
So yeah, first step is either making your own swing mechanic or understanding how the other one works
Otherwise you’ll run into similar problems over and over again as you add new things
while i start looking through the code, what are some things to look out for? what do rigidbodies not work with?
what exactly wasnt making it work ? explain what "didnt work" meant
Don’t look for anything specific, understand how every aspect of the swing mechanic works and then it should make sense why the rigidbody screws it up
And also, this ^?
in the game, theres a red orb that shows where the cursor is or the nearest available spot for the grapple raycast thing to align to. it shows up on the building before rigidbody, and doesnt show up after, thus you cant grapple swing from that spot
is the building marked as static on the inspector?
maybe the rigidbody was pulling the collider down
oh, its not static
so if i make it static, the rigidbody could potentially work then?
hmm adding rigidbody wuold normally make the building fall
nahh you would add it as kinematic
i turned gravity off
when i did the rigidbody
and locked the rotation and position
so, instead of doing rigidbody, add a kinematic?
kinematic is part of rigidbody
kinematic fixes the swinging issue, but having a rigidbody doesnt seem to fix the triggers
the start works though
did you give the building both collider and rigidbody
and which one has trigger
buildingprocedural_gen has the script, refers to defaultcube, defaultcube has rigidbody and a meshcollider, and its child, new_building_trigger, is the box collider set to be a trigger
trigger collider needs the script or the rigidbody need script, either one
also u have to show hierarchy its hard to tell who child of what
sorry, here you go
ill try putting the script on default cube then
oof I put it on default cube, and now my cursor is locked and I cant stop the play
You should have not put it on the cube you spawn
you crated an infinite loop 
recursively
then what should I put it on, if I cant use the empty I was using previously or the cube
never good idea having object spawn itself
like why would building spawn, detect another building and spawn another copy and keeps going without reason to stop
you only need 1 spawning script
you told me that the script needs to be on the building, so thats what I did lol
that was before I saw trigger was child of each building
your setup was confusing tbh lol
fair lol
can you tell me again why is building carrying a trigger to detect another building ?
that... is an excellent point
I thought the trigger box would detect the player entering/leaving though lol
well how do you want them to spawn exactly ?
yeah but you're checking Tag of a building not player
I was wanting a building to spawn if the player enters the trigger, and the building destroying when the player leaves its zone
is player rigidbody ?
no
Character Controller ?
ok so keep the trigger on building put the tag there, then the script should be maybe on the player
each time you enter a trigger you can find the parent /building it is and + that to new spawn pos
so the only thing im changing is the script location to player for this test
yea first see if the log prints when you enter newbuilding trigger
ok sweet the code works now! now I gotta tweak it, cus it was like a building-apocalypse lolll
and it spawned behind the player, which i dont want
woo progress!!!
hmm yeah you would need to work with some trig math here if you want a good result
Dot product would be your best friend
luckily unity has these built in
slider.OnValueChange doesn't work
debug it
In Start()
slider.onValueChanged.AddListener(OnDifficultyChange);
private void OnDifficultyChange(float value)
{
Console.WriteLine(value);
}
Anyone know why this doesn't work? I want the speed of the particles to be proportional to the speed of the rigidbody2D (rb2d)
ParticleSystem p = Instantiate(leaveBehind, transform.position, Quaternion.identity);
var main = p.main;
main.startSpeedMultiplier = rb2d.velocity.magnitude;
is the script running?
Yes. To be exact there are more lines after this that work just fine like
main.startColor = particleColor;
So the references and all are there, but startSpeedMultiplier doesn't seem to do anything?
maybe you just wanna change the startSpeed specifically, https://docs.unity3d.com/ScriptReference/ParticleSystem.MainModule-startSpeed.html
I've tried that, problem is that means all praticles have the same speed. I want them to be random between two constants but scale with the velocity
Alrighty resolved. Solution: I don't know dawg. But I scaled the particle's simulation speed and lifespan propotionally instead and that kinda is the same thing. 
Hi Everyone,
I have 3d avatar character game object and camera in Unity Scene.
- How can I restrict the movement of camera when distance between character object and camera is very close?
- Is there any option to restrict the camera movement using object collision?
- How can we restrict camera movement within a specific boundary using C# script?
Kindly anyone provide suggestions to achieve it.
easiest way would probably be starting with Cinemachine
how can I get the ontriggerexit function to destroy the building the player is leaving? not necessarily the building being created in ontriggerenter, but the one the player is currently leaving?
not only does the on trigger exit not work, but it causes buildings to stop spawning
dont post screenshots of !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProceduralGen_Building : MonoBehaviour
{
bool IsCollision = false;
// Start is called before the first frame update
void Start()
{
Instantiate(Building, new Vector3(Random.Range(40, 61), 0, Random.Range(40, 61)), Quaternion.identity);
}
// Update is called once per frame
void Update()
{
//transform.position += new Vector3(0, 0, -10) * Time.deltaTime;
}
private void OnTriggerExit(Collider other)
{
IsCollision = false;
waitFiveSeconds();
if (IsCollision == false)
{
other.gameObject.tag = "Destroy";
}
if (other.gameObject.CompareTag("Destroy"))
{
Destroy(Building);
}
}
public GameObject Building;
private void OnTriggerEnter(Collider other)
{
IsCollision = true;
Debug.Log(other.gameObject.name + other.gameObject.tag);
if (other.gameObject.CompareTag("New_Building_Trigger"))
{
Instantiate(Building, transform.position + new Vector3(Random.Range(40, 61), 0, Random.Range(40, 61)), Quaternion.identity);
}
}
private void OnTriggerStay(Collider other)
{
Debug.Log(other.gameObject.name + other.gameObject.tag);
}
IEnumerator waitFiveSeconds()
{
yield return new WaitForSeconds(5);
}
}
Debug wether OnTriggerExit is even called
also you cannt start coroutine like this waitFiveSeconds();
since it does not do what you think it does
it shows up or something cus it causes the code to stop working or stop spawning stuff
its just empty
so do waitFiveSeconds(5);?
wat no, this isn't a guessing game lol
that wasnt a guessing game, that was me thinking thats what you meant and seemed logical to me
"it shows up or something" is not how you debug...
how can i hide a ScrollView without disabling it?
how many vertexs can i have on a model without losing performance
somewhere between 1 and 1 bazillion
does anyone have an idea of why this is caused? im not that good with unity and doing this via a tutorial so i dont really know what everything means
well, for one you should connect vs to unity
i did yesterday, i updated it via the thingy someone linked
How many dollars do I need to feel happy?
It's still not configured !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
im confused then? because i followed the first and the 2nd one, which one do i use them?
The second should be enough
Share a screenshot of the unity workload installed in vs and the correct ide selected in unity external tools
This and unity workload in VS
It's one of the steps. You should know it.
you want me to take a pic of this? i woke up like an hour agho with like 3h of sleep im not functioning well im so sorry
The whole window with unity workload visible
It doesn't look like you have it from this screenshot though
Okay. I assume you did install it before and didn't just tick the checkbox now.
Try regenerating project files in unity external tools.
I think so. Can you take a screenshot of the whole window?
Yeah, that's configured correctly.
thats iut
because i did this from a tutorial
and i deleted EVERYTHIGN thinking i made a mistake and followed everything as close as possible, but it's the same mistake
The error implies that there is no EnableOutline() method in the Interactable class. Is there?
uhh, you mean something it can refer back to? because that EnableOutline() is the first time i've used it
Didn't you say it's from a tutorial?
Now compare the name of the method you call and the one defined in this class
Wdym?
EnableOutline is only mentioned in this script and the other
it also says 0 references
Yes, because you're not calling it from anywhere
OutLine and Outline ?
And the method you're trying to call doesn't exist
i might
just be stupid
🥹
hello I'm quite new at unity, is there anyone who could lend me a hand and teach me the basics? I would like to make a game but I'm currently doing all the planning and animation and coding is just overhelm me a bit yet
I would suggest picking up the basics of C# first. A lot of people start out with Unity tutorials that SOUND simple, but without the fundamentals they quickly get overwhelmed.
Once you understand variables, methods, fields and classes, you should have enough to bite into the simple tutorials without feeling immediately lost.
I have the basics of programming in other languages (html,css,java,python)
but I understand what you say
I just got really excited and wanted to jump into
idk seems laggy to me
it would be much better if I could find a cooperative programmer and leave the unity to him but I cant afford it
Woah. How many verts does this thing have?
And what would you contribute?
idk 4m i think
Okay.
Well.
That's probably too much.
For comparison high detail human models usually have 20-60k tris.
!collab👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Where did you get this tree?
Like I work with high detail brain models that usually clock in at 140k per hemisphere.
So 4m is like.
Nuts.
I mean, it depends. If he's making an ant simulator and the tree is the whole world, then it's fine.
Alright that's a fair one I guess.
I'm making the art and animation also I have the game design
thank you
Well what does your art look like?
How does it work with OnTriggerEnter for child objects when having multiple colliders on an object?
pretty basic 2D yet, but improving every day
also I have a friend who working on the sound effects and the music
Wdym by "how does it work"? It works the same as with one collider.
From what I've read on forums, OnTriggerEnter should still be fired off even if put on the parent object, but I don't seem to be getting a response.
It would be called either on the collider or on an attached rb. If the collider belongs to the rb.
It wouldn't be called on the parent for no reason
Wouldn't
Ah right, just asking, but would it be bad practice to move a trigger to use it as a "second" trigger?
No clue what that means
Just to give a short explanation what I'm doing, I wanna check if the player touches the left trigger and then activate the right trigger to see if the player goes back.
So would it be bad practice to change the transform position and just write some code around that? Or is there a better/easier solution
That sounds fine.
Change position of what?
The collider.
Why change it's position?
To check if they go back as I said
Just use a second trigger🤔
Yep that's what my original question was about, but I can't add 2 colliders to the single object 😁
Doesn't allow me to change the second collider
You can...🤔
I'm actually not even sure which collider causes an OnTriggerEnter first if there's multiple on the same object.
You'd think it would go down the list but knowing Unity it might be random.
void Start()
{
firstCollider = transform.GetChild(0).GetComponent<BoxCollider>();
secondCollider = transform.GetChild(1).GetComponent<BoxCollider>();
firstCollider.enabled = true;
secondCollider.enabled = false;
}
I've tried this
Well, "undefined".
That's 2 colliders on 2 objects.
That's 2 colliders on 1 object
Which of the setups do you have actually?
I just added this to show you I can't change the second collider if 2 are on 1
Right now I have this.
You should be able to
But the problem is that I can't get the trigger from them in the parent object that has the script.
But yeah, it's better to have 2 objects
The picture shows I can't 😁
The button is missing
It doesn't show me anything like that
Aah, that
You can still edit the numbers in the inspector
But if I then call OnTriggerEnter
Which would it get
And how would I disable the SECOND component
You can expose fields in the script for the box colliders and just slot them in
then modify them in code
The one that has the collider
Alright perfect let me try
And if you want to shoot yourself in the foot you can use GetComponents and then access the collider components with [0] and [1] 🙃
@teal viper can you tell me if splitting one big coroutine in bunch of smaller ones is a good idea?)
How big we talking?
Mm.. depends on how you do it. What's the purpose of splitting it though?
I have a coroutine that runs for each unit acting in turn-based game. And there are 3 paths split by if statements depending on whether unit uses magic, melee or non-damage ability. So was thinking if splitting them into 3 diff coroutines would be a thing
That sounds pretty long. I would only split it up if the actual yields are complicated. If it's just a lot of regular code split up by the occasional yield return new WaitForSeconds then I'd just take the complicated code out, put them in methods, and call the methods.
Having those "yield return new waitforseconds" is crucial there... thats why its a coroutine
Sure, why not
Sure but if the code is like
yield return new WaitForSeconds(2);
//Spawn and fire magical bolt at target (~100 lines.)
yield return new WaitForSeconds(1);
Then just move the complicated logic out of the coroutine into methods, and then just call the methods.
You can move the yield lines to methods as well, if you call them with yield return OtherMethod();
How can I hide an object without disabling it
because if i disable it ill be disabling the box collider
disable its renderer
fair
Actually great idea. That's what I was thinking about. Thank you!
i only have 2-3 hrs left for this
so i have two 3D objects but display with an orphographic camera so they look like 2D UI
they are processed with a plugin called megafier
and displayed by a special camera
however, one of the object size will go off, like it couldnt maintain the same ratio under different resolution ratio
my question is, can you force the camera that display the gameobject , to display it with a fixed screen size?
Hi , anybody can send a tutorial for make main menu for a 3d game ?
string timeStamp = System.DateTime.Now.ToString("yyyy-MM-dd h:mm");
string filePath = Path.Combine(Application.persistentDataPath, "datos_" + timeStamp + ".txt");
I have problems with the date format but I don't know why
Does anyone have any idea why i cannot pick this up? it's supposed to have an outline around it when im close to it with some text saying to pick it up, but when i press F nothing happens
it's also supposed to dissapear when i press F
Are you planning to tell what problems you're having or are we supposed to guess?
Where are you calling CheckInteration ?
Ya need to start learning how to debug your code and such that when I look at this code it should be riddled with debug.log statements
it's unused i think
ok well debugthe currentInteractable make sure its not null
im doing it via a tutorial and i really dont know how to make like, any code at all
sorry, I want to create a .txt with that name, and it gives an error Could not find a part of the path "C:\Users\PRACTICAS1\AppData\LocalLow\DefaultCompany\AVRIX\datos_ 2024-03-15T10:09:57Z.txt".
and how to enable the renderer again once the player dies/scene ends/next level
{
Debug.Log("pressed");
}``` learn about debug
You can't have the : character in filenames
that works
i just don't know why it doesn't outline and pick up the object
i extended the player reach thinking that might help, but that also did nothing
ok so that works then, so you next debug should be the currentInteration.Interact
ty
I dont no your full script but im guessing your using ray cast to detect the hit to pick it up. Add a fixed update and call your ray cast funtion inside that. private void FixedUpdate() { CheckInteration(); }
yes inside there add a debug.log to see if your even calling it
if it does not work add this private void FixedUpdate() { CheckInteration(); }
where would i add the debug? im a 3d artist i dont know anything abt this 🥹
im so sorry
top line inside this function
ok so where the { is
try it
both get a whole lotta red lines on the code under it
no revert that.
you have deleted your original function name
Fixedupdate is its own function
OH
the vertical layout group im using is forcing the panels inside to occupy 100% of the content
way too tall
im lost
like i know what it means, i just dont know how to tie it together into like
actual code
like where do i put this n that
void CheckInteraction()
{
RaycastHit hit;
}
this is your function
nvm i fixed it
to debug it do
void CheckInteraction()
{
Debug.Log("am i being called");
RaycastHit hit;
}
nice pfp
ty
if that is being called then you need to keep going down your list with debugs, you can even check varables.
if that debug is not being called then that means you are not calling it on that script
uh i dont think im calling it
this is correct right
i feel like my issue is with checkinteraction then
private void FixedUpdate()
{
CheckInteraction();
}
void CheckInteraction()
{
Debug.Log("am i being called");
RaycastHit hit;
so then i would call it and check ifthat fixed it
raycast is a physics function so your want to call it in fixed update rather then update as its physics
ok so is that working because you added fixed update?
there you go
take a debug couse and also learn c# basics
other wise your always running uphill
I am getting an error called Boxcollider does nut support negative scale or size where can I get help with this issue?
Make sure your object doesn't have negative scale
Or size
I was watching a tutorial and he did the same thing but he wasnt getting any errors. what should I do then if I want a reversed object?
Why do you have a 3d collider on a 2d object, is that intentional?
Anyway you can just rotate it 180 degrees instead of negative scaling
oh no its a mistake
alright thanks
okay so i have different types of enemies and i want to make a "wave manager" that spawns them randomly, this is my aproach:
New enemy generation system:
Create a list
loop:
Have x amount of coins depending on the wave
Let each enemy have a value in coins
add enemies to the list randomly until you reach 0 coins
Start instantiating enemies while deleting them from the list until there is no more enemies remaining
set the amount of coins to x number for the next wave
Increase wave counter
(would this make sense?)
i´ve just learnt how arrays and lists work and thought this could be a good way of using them
we’ve all been there
Some more often than others
The forbidden semicolumn
are the instructions "return,jump,break,continue and goto" something that i should learn as early as possible?
take you 2 seconds to learn it
You can skip the jump and goto. Everything else is crucial. You can't really write functional code without it.
then imma just do it
is continue that important?
Yes.
if you want to (dont feel obligated) and have some time, would this make sense
Makes sense.
Hey! I probably have a stupidly simple question, but here we go: What would a GameObject that shows a 2d matrix on the editor, look like? (as a script)
So in practice I want to see a 500 by 500 grid on the screen (2d) and every other block be white/black.
Background: I'm trying to figure out how to just output stuff in the world, from a empty gameobject script. I haven't done unity or c# before, but I work full time on typescript/python.
That would probably require a custom shader.
Hmm, got some links towards that?
I can probably figure it out, with the right direction 😅
Google unity grid shader
Probably not gonna be exactly what you're looking for, so you'll need to figure it out from there.
Hmm, let me see, just a second 
This at least one of the things I'll need a bit later. I think I'm looking for something more basic like console.log("X") in JS that would output into the console, but instead it be Some C# code in GameObject script -> Box/Grid shown in scene view
Maybe I'm looking for the information/docs on "how unity turns gameobjects into stuff in game world"
Sorry for being a bit weird with the questions 
It doesn't.
There's Debug.Log() if you're looking to log something in the console.
As for documentation, there's !docs
And !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi guys I gave a problem with my script I am making a horror game and when there's a Jump scare there should be a Chromatic Aberration effect which show up to this point everything works, but the main problem is I am trying to let it fade out, and it doesn't work I tried Using an I Enumerator and Also a method i am also calling it right but i doesn't want to work
void HandleChromaticAberration()
{
if (UseChormaticAberration == true)
{
if (chromaticAberration != null)
{
chromaticAberration.active = true;
chromaticAberration.intensity.value = 0;
isFading = true;
if (isFading)
{
intensityTimer += Time.deltaTime;
float t = intensityTimer / fadeDuration;
chromaticAberration.intensity.value = Mathf.Lerp(1f, 0f, t);
if (intensityTimer >= fadeDuration)
{
isFading = false;
}
}
}
}
else
{
Debug.LogError("Chromatic Aberration reference is null.");
}
} ````
Share !code ptoperly
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hmm. So to just splurge what I have here: I have a 2d matrix data source and all of the "cells" in that 2d matrix hold the following info type: string; color: string; opacity: number;. I'd like to display that in the game world (as 2d), but from a single GameObject 
You probably mean a 2d array? Not a matrix.
You have several options: either instantiate objects(planes or cubes) for each cell and change their color or write a custom shader to draw your grid in one GPU command.
What exactly doesn't work? Are there errors? Compile errors? Runtime errors? Does the code even run? Where are you calling the method from?
Ah right, yeah that's what I meant 😅
How well does Unity handle a sizeable amount of objects? Let's say 6 million?
It depends on how you render them.
It can be anywhere from very fast to slideshow.
Hmm, alright. I'll probably go with the custome shader route, since that is more or less guaranteed to not be a slideshow 
Thank you a ton!
the code is running it show up the effect but i dosent decrased it
on screen
there are no errors or compile errors
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Object.SetActive(true);
HandleObjectAnimation();
HandleChromaticAberration();
if (UseSound == true)
{
TriggeredSound.Play();
}
}
gameObject.SetActive(false);
}```
there is the method begin called
does someone know why goto doesnt work here?
Labels end in a colon, not semicolon
in this: , ?
but please don't even try to learn goto. It's generally considered bad practice
its already in a while loop but since i dont want the money to go into "debt" i want that whenever it buys a random thing that has more price that it can afford it gives back the money and goes back to buying other item instead
You can do that with just continue
but then it doesnt go back to the start does it ?
Yes it does. That's exactly what continue does.
ohhhh
then i understood what it does completely wrong
which makes sense since then it would have no use
ty and sorry for my dumb ahh
oh another thing
nvm i figured out a tricky way
any idea what this could be about?
ive never encountered this error before
i have a feeling its because its trying to access a script from a different scene
So it's only called once. Obviously, any logic that runs over time wouldn't work.
Definitely that. Unless you have several scenes loaded at the same time, objects in the othe scene don't exist.
im assuming DontDestroyOnLoad only works if changing scenes via script rather than loading them in the editor
null reference exception means that you're trying to access somethin in null. You can see the line that causes the issue in the callstack.
Yep.
It only works at runtime i think
ok sick so this should work when i make a scene manager
Hi guys, anyone know how i can fix this error please ?
My class Quest :
public class Quest : MonoBehaviour
{
public QuestName questName;
public QuestState questState;
public QuestType questType;
public QuestRewardType questRewardType;
public int questRewardAmount;
public string questDescription;
public Vector3 questLocation;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
The class producing the error :
[System.Serializable]
public class QuestManager : NetworkBehaviour
{
public static QuestManager Instance { get; private set; }
private SyncList<Quest> activeQuests = new SyncList<Quest>();
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
}
public void CreateDiscoveryZone(Vector3 location, Quest quest)
{
Debug.Log("CreateDiscoveryZone");
// Create zone...
}
public void ActivateQuest(Quest quest)
{
activeQuests.Add(quest);
}
public void CompleteQuest(Quest quest)
{
// quest.Complete();
activeQuests.Remove(quest);
}
}```
can you not access this in the inspector?
Share the error details
No
so ill have to reference like this?
at Unity.ILPP.Runner.PostProcessingPipeline.HandleDiagnosticMessages(String ilppName, List`1 messageList, LoggerAndProgressSink& combinedLogger)
at Unity.ILPP.Runner.PostProcessingPipeline.PostProcessAssemblyAsync(PostProcessAssemblyRequest request, Action`2 progressSink)
at Unity.ILPP.Runner.PostProcessingService.PostProcessAssembly(PostProcessAssemblyRequest request, IServerStreamWriter`1 responseStream, ServerCallContext context)
Unhandled Exception: System.InvalidOperationException: Post processing failed
at Unity.ILPP.Trigger.TriggerApp.<ProcessArgumentsAsync>d__1.MoveNext() + 0xf74
--- End of stack trace from previous location ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
at Unity.ILPP.Trigger.TriggerApp.<ProcessArgumentsAsync>d__1.MoveNext() + 0x1149
--- End of stack trace from previous location ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42
at Unity.ILPP.Trigger.TriggerApp.<RunAsync>d__0.MoveNext() + 0xc7
--- End of stack trace from previous location ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42
at Program.<<Main>$>d__0.MoveNext() + 0x1a3
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb6
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x42
at Program.<Main>(String[]) + 0x20
at Unity.ILPP.Trigger!<BaseAddress>+0x47849b
Why do you need the scene reference?
ig so i know which scene I want to change to
but youd just use buildindex anyway right?
Are you using mirror?
Yes
yes !
Do i need to call it in update?
I assume the issue is using Quest in a sync list. Because it's a MonoBehaviour, Mirror can't serialize it.
In update or a coroutine.
srry for the stupid question but how can i make the script know wich one is the first gameobject of a list? context: i have a list of enemies that will spawn that round, my goal is to take the first gameobject( enemy) from the list make a var gameobject equal to it, spawn one, remove the gameoject from the list and keep doing that in a loop until there are no remaining.
Ah okey I will try that
Well, how would you access the first element in an array?
Yes.
it starts with 0
i forgot completely 💀
my memory is ass
so i just do what i wrote with a 0 instead of a 1?
Yes.
Yeah, i found the error, thanks anyway 😉
im running into a weird issue where this is only going through when false rather than when true like it should be
any ideas on what could be causing it?
I 100% guarantee you are mistaken
Add another log inside the if statement
And add an else if you need to
And make sure Collapse is not enabled in your console window
https://gdl.space/epohaweyex.cs this is the settings script and this is the script from the screenshot https://gdl.space/tecaxezebe.cs (line 157)
fullscreenEnabled != fullscreenEnabled just fyi a neater and better way to toggle
ok, so explain why you think the if statement is working backwards?
i saw that when i was researching into how to do it but that syntax confuses me
! negates a bool
it turns true into false and false into true
so it returns false but the if statement goes through
no..
the else is running
and printing that it's false
the if is not running
ok but that's not being shown here
clearly the else is running
because it's printing false
You should really use better logs
to be more clear
Debug.Log(SettingsScript.main.tutorialsEnabled);
if (SettingsScript.main.tutorialsEnabled)
{
Debug.Log("Tutorials are enabled, activating the menu");
tutorialMenu.SetActive(true);
}
else {
Debug.Log("Tutorials are NOT enabled, NOT activating the menu");
}```
so yeah the else is running
yeah exactly
but i have no idea why the tutorial gets toggled on then
ill look around if anything else is doing it yeah
maybe something in LevelManager.Pause?
it might be because i left the tutorial menu on in the other scene 😭
let me test it now
ok now its just not setting it active
whats the ctrl F shortcut but for the whole solution?
that is not a valid syntax
Depends on the "something"
its a string array
probably has something in it at times
do i have to loop everything an remove them 😭
new string[0];
Then you create it as a new string array
If you want to remove things, you'll need to use a list.
i want my array to be empty
an empty array is a 0 length array, and can't hold anything
you really want a List
to clear a list is myList.Clear();
or ill just go learn lists again
for an array, you loop through and assign them all to null
but that doesn't make it empty
it makes it full of nulls
of course
that's what = is for
it's wasteful generally to do that though since you'll be discarding the old array
which means it needs to be garbage collected
Using a List you can reuse the same memory and still resize it
i have not used arrays at all. is there any time that one might be used?
i just seem to default to list
when you know the number of things isn't going to change
cool
What component do i use with Navai for it to mark the map as walkable
why this doesnt work?
because it doesn't make any sense at all?
Find needs the name of the object you're looking for, as a string
sorry i forgot the whole line 💀
GetComponent<RocketMotor>() is going to return the RocketMotor component that is attached to the GameObject this script is attached to
Do you mean navmesh? Or what's Navai?
What unity version are you using?
the version is in the window title
Then you'll need to use the navigation tab to define the areas
https://docs.unity3d.com/2021.3/Documentation/Manual/nav-AreasAndCosts.html
ok i tried biding my player in a new scene today and i keep getting this and i have no clue of why its happening even tho it works perfectly fine in the test scene
Player movement: inventory open function
{
canMove = true;
}
private void OnEnable()
{
EventBus.Instance.onOpenInventory += () => canMove = true;
EventBus.Instance.onCloseInventory += () => canMove = false;
}
private void OnDisable()
{
EventBus.Instance.onOpenInventory -= () => canMove = true;
EventBus.Instance.onCloseInventory -= () => canMove = false;
}```
EventBus
private void Start()
{
canMove = true;
}
private void OnEnable()
{
EventBus.Instance.onOpenInventory += () => canMove = true;
EventBus.Instance.onCloseInventory += () => canMove = false;
}
private void OnDisable()
{
EventBus.Instance.onOpenInventory -= () => canMove = true;
EventBus.Instance.onCloseInventory -= () => canMove = false;
}```
Share the line that throws the error
EventBus.Instance.onOpenInventory += () => canMove = true; should be the error line
EventBus.Instance is null
also you pasted the same code for both files
The intention was for them to figure that out...
You can see that the only thing that could possibly be null on that line is EventBus.Instance yes @quick kelp ?
line 33 is the error
EventBus.Instance.onOpenInventory += () => canMove = true;
That's fine. I just like using situations like that to teach them to read errors.
i read the error i just dont get how the error is now poping up as soon as i copy and past things from the test scene into the new scene
You're focused too much on that circumstance of copy and pasting
think about the error and the code
you're trying to access Instance before it's assigned
Hello guys i have a question what is better to achive ground check on 2D OnCollisionEnter2D or OverlapCircle()?
overlap
I concur . . .
Why overlap?
collisions can happen anywhere
if you bump your head, that doesn't mean you're grounded
Another problem my player's rigidbody interpolation is interpolate and im on a moving platform and i try to move with rb.velocity it doesnt move if im at interpolate so i add the platform speed to player it fix but do a lot of calculations is there another way to fix it?
interpolation doesn't affect the actual motion of the body at all
No for example im on moving platform that is the player's parent while he collide with it if player's interpolation is none or extrapolat and player move its fine but he looks wired beacues its extrapolat and not interpolate
if he is interpolate he cant move
or move very slow and wird
It's not interpolation that is the problem it's your movement code
setting the velocity directly is going to mean the platform can't impart any velocity to the player
interpolation doesn't affect the movement
it only affects the visuals of the movement
But isnt rigidbody.velocity the propare way to move?
there is no "proper" way to move
like this rb.velocity = new Vector2(moveSpeed * moveX, rb.velocity.y);
there are different ways with different drawbacks and advantages
The most physically realistic way is to only use AddForce
And it will fix the moveplatform problem?
it will allow your platform's friction to affect the player
"fix the problem" is a massive oversimplification of what it will do
i changed the moving platfrom movement from rb.moveposition to vector3.movetowards cuz rb.moveposition was laggy
Sounds like you were usng MovePosition inside Update instead of FixedUpdate
no
you don't seem to have a grasp on what the code is doing
MoveTowards doesn't move an object
it's just a math function
Ye but i move it toward waypoint
you want to figure out what sort of player you want first tbh.
Do you want precise snappy movement like Mario, or flowey ragdoll-like movement.
Like hollowknight smooth movement
it would need to be combined with some other thing like rb.MovePosition or rb.position = to actually move the thing
you can use MovePosition WITH MoveTowards
as long as it's in FixedUpdate and interpolation is enabled it will be smooth and correct
Hollow knight would probably be done by dynamic rigidbody, where forces add, like Praetor says
ye bgut i fixed it with vector3.movetward the waypoint
Loup addforce? why not velocity
because they wanted realism
Just FYI, by the way, the only thing AddForce does is change the velocity
ultimately the only thing any of these things are doing is changing the velocity
setting velocity effectively deletes all history of an object’s momentum
So velocity is like mario movement right
it's just a matter of whether the change to velocity is taking current velocity into account or not
mario famously has realistic momentum to his movement
adding force additively adds the contributions of multiple different things that can modify your velocity, and continuously adds it to your current velocity. It keeps momentum easier
guys is there a way to clone thats not looping throught the entire list and creating a new list?
so addforce on horizontal and jump?
define "clone"?
if you need a second list, you have to create a new list one way or another
new variable thats not a reference
all your variables to lists will be references.
But you want to create a new object and reference the new one
mario turns on a dime, praetor. There is a little bit of simulated drag added for more fluid motion, but Mario would 100% be setting velocity constantly.
new List<Whatever>(oldList) will create a new list with all the same contents as the other list.
I disagree
mario has momentum
Guys what instead of addforce and velocity i can add to the horizontal movement? that hollow knight or other games did?
hmmm. i tried that but didnt work. but i mighve done smething wrong. thanks
i mean in addition
also note that "Mario" is describing like 25+ games over the decades
addforce is good tho.
the world of mario as a whole sucks at transfer of momentum, which is core to a dynamic rb simulation. Objects in mario can only receive/transfer momentum with a single surface at a time.
just a little video i made comparing how each 3d mario (that has a dive move) differently treats mario's existing momentum in the dive. 64 and sunshine overall have much more momentum-based physics than any of mario's later games, but i thought the dive in particular was a good comparison to clearly show the difference. the odyssey/3d world dive...
i’m focusing on the base mario titles. Except sunshine, which definitely used something more like add force
mario basically invented the idea of momentum in platformers
Sunshine mario plays very different to every other 3D mario
Show what you've tried
mario is very different from madeline in celeste, who activelt recieves momentum and forces from everthing she touches, and multiple things at once.
The list constructor definitely should take a list and create a new list with the same contents
i need a better ide for real
Use Rider
i dont think they have a community version
man mario 64 was so ahead for its time
K and on the jump should i use addforce or velocity? and what to add pressure jump? double jump? maybe wait a bit before jump and fall?
Mario has a concept of momentum, but it is not based on physics. It is one based on reference framing, relative to the velocity of the one surface you ride. eg floor/wall
I always set velocity for jump so that jump can be a consistent height regardless of your current velocity.
It's based on physics - it's just a different physics simulation than we're used to in Unity
all of these are physics simiulations of one kind or another
If your jump is based on addForce, then when you are on a falling platform, and jump, then you can jump while still having downward velocity
setting world velocity gives a constant jump height in the ref frame of the world
rb.AddForce(new Vector2(moveSpeed * moveX - rb.velocity.x, 0), ForceMode2D.Impulse); is it good addforce movement for horizontal? moveX is getaxisraw
that should be force mode
horizontal movement should usually be additive
regardless of what sort of character controller you have
When i do force mode to be good speed the movespeed should be like 400
depends - where are you adding the force?
AddForce ForceMode sets vel += deltaTime * force / mass; at end of frame.
(at least in 2D)
any impulse mode force can be expressed as a force mode force by math
So impulse is like rb.velocity?
but you usually use impulse mode when you want to apply force once. Like a sudden yeet/collision
force mode is intended more for a force that acts over multiple frames
i forget the exact equation right now, but that is the general idea
But when im using force mode my move speed has to be like x100 higher idk if its right
No.
velocity = SETS the velocity
AddForce ADDS to the velocity
you can think of AddForce as velocity +=
So addforce is like with acceloration right?
and in 2D, impulse mode IMMEDIATELY sets velocity, on that line
the only thing the forcemode does is change HOW MUCH the velocity is changed
Like realistc movement with acceloration?
Im trynna make a very simple gun in unity, but the sphere goes straight down whenever i shoot
AddForce force mode should have an input of force in units of Newtons (kg m/s^2)
Here's the real deal
AddForce(x, ForceMode2D.Force) is the same as rb.velocity += x / rb.mass * Time.fixedDeltaTime;
AddForce(x, ForceMode2D.Impulse) is the same as rb.velocity += x / rb.mass
let me just double check the math rq
and velocity doesnt take care about rb.mass?
velocity is just m/s
K so if i want acceloration so i need Addforce
but how can i controll the accerolation
hey guys, unrelated to current disscusion, fairly new to unity, quick question, what would be the best way to not display a node without setting it inactive ? for context i have an empty node with just a script that serves as a parent for my menu, problem is if i set it to inactive the script stops listening (if im correct), is there a trick like adding a node that can be set to not display somewhere ? Tried looking it up didnt find anything satisfying
velocity is literally velocity. It's just how fast the object is moving and in what direction
Disable the renderer, or whatever the visible component is
velocity is whatever the hell you set it to
so disable the childs renderer* rather tha nthe parent directly ?
if you set it to a differnt thing each frame, it will certainly not stay the same
So almost every good game use addforce?
or the whole child object. Whatever makes sense for you
tyu
every good game uses the thing that makes sense for that game
every game is different
Also as I explained here AddForce can be recreated using the velocity property anyway
Like i use velocity and i fill like my movement a bit wird and slow aswell the jump
double checked, this is right
feel
I tried adding force to player rb.AddForce(new Vector2(moveSpeed * moveX - rb.velocity.x, 0), ForceMode2D.Impulse); but it feels like abit slow and with delay
idk if i did the addforce right
you probably did not adjust any of the numbers
Maybe the problem is the movement speed value or gravity how can i find a good values?
Is there like a way to check the gravity compare to the speed value?
jump velocity i calculate through kinematic equations, where I input a desired Jump height (meters) and time to reach the top of the jump (sec), and input gravity (m/s^2), and i calculate the initial jump velocity that satisfies it
K and genral question the way im using addforce here is fine? rb.AddForce(new Vector2(moveSpeed * moveX, 0), ForceMode2D.Force);
this will add a force to your character proportional to your move speed and how much you tilt the controller, and increase without bound
which will let you go to arbitrarily high speed
nvm found it, character rotation was wrong
//Calculate gravity strength using the formula (gravity = 2 * jumpHeight / timeToJumpApex^2).
gravityStrength = -(2 * jumpHeight) / (jumpTimeToApex * jumpTimeToApex); // = acceleration in units/s^2
//Calculate the rigidbody's gravity scale (ie: gravity strength relative to unity's gravity value, see project settings/Physics2D)
gravityScale = gravityStrength / Physics2D.gravity.y;
// Calculate forces. mpulse force is more like velocity. Use my own kinematic eqn. Based on vf^2 = vi^2 + 2a*dist
jumpForce = Mathf.Sqrt(Mathf.Abs(gravityStrength * 2 * jumpHeight));
this is how I calculate my jump force
But about the horizontal movement
I want smooth stable speed
maybe when i stop very little bit move slow like hollow knight
public void AddForceAlongGround(float targetGroundSpeed, float accelRate, bool shouldBeOnGround) {
Vector2 slopeNormalToUse = contacts.currentBase.slopeNormal;
// This will make it possible but very slow to climb steep slopes.
if (Vector2.Angle(Vector2.up, contacts.currentBase.slopeNormal) > KinematicPhysics2D.MAX_SLOPE_ANGLE // Slope too steep
&& (contacts.currentBase.slopeNormal.x * targetGroundSpeed < 0)) { // Moving into the slope (negative number);
targetGroundSpeed = 0f; // Bring to full stop
}
// Scale by slope normal.
Vector2 alongSlopeVec = Vector2.Perpendicular(slopeNormalToUse); // points in negative x
Vector2 targetSpeedVec = new Vector2(targetGroundSpeed, alongSlopeVec.y * targetGroundSpeed / alongSlopeVec.x);
//Calculate force along x-axis to apply = speed difference * acceleration rate. Units are pretty fucked here.
Vector2 newForce = (targetSpeedVec - rigidBody.velocity) * accelRate;
// No Y component if not grounded OR if jumping etc
if (!shouldBeOnGround) { newForce.y *= 0; }
//Convert this to a vector and apply to rigidbody
AddForce(newForce, ForceMode2D.Force);
}
This is the code I use for running
I have more bools and things here to deal with slopes
hm its for 3d game?
I dont have slopes
There isnt a simple way to make like this rb.velocity = new Vector2(moveSpeed * moveX, rb.velocity.y); look a bit better?
add some interpolation?
then just skip the part about my slopes, and do the math for slopenormal = Vector2.Up
rb.velocity = new Vector2(moveSpeed * moveX, rb.velocity.y); you mean i can add accelrate to it?
Vector2 targetVelocity = new Vector2(moveSpeed * moveX, rb.velocity.y);
rb.velocity = Vector2.MoveTowards(rb.velocity, targetVelocity, 4 * Time.deltaTime);```
Some simple interpolation for example
You combine physics with not physics and physics with time.deltetime and not time.fixeddeltatime is it k?
I am not doing anything here that is non physics
rb.velocity
I am moving entirely with rb.velocity
its physics
In FixedUpdate Time.deltaTime == Time.fixedDeltaTime
MoveTowards, as I said before, is a math function
oh
it has nothing to do with moving any physical objects
i'm using it to "move" the velocity
the relevant part of my code that does not include slopes is:
AddForce(newForce, ForceMode2D.Force);```
K and the 4 is instead of movespeed? and is it fine to do it in 1 line?
hello, could somebody help me with unity collision 2D?
accel rate is kg/s, which is 1 over how many seconds I want it to take to reach max velocity, and make it independent of mass
b.velocity = Vector2.MoveTowards(rb.velocity, new Vector2(moveSpeed * moveX, rb.velocity.y), 4 * Time.deltaTime); is it fine i do it in 1 line?
why do you care so much about doing it in one line? You should be focussed on doing it right
have you ever heard the saying that the compiler is smarter than you?
well, the compiler is smarter than you
write your code well in a legible way. And even if the compiler were not smarter than you, a new vector is one of the most insignificant costs, and terrible reasons to make your physics code harder to read
you will need to do a LOT of modifications to physics code to add features and special cases in the future. you cannot afford for it to be challenging to read just to save a line.
k but Vector2 newForce = (targetSpeedVec - rigidBody.velocity) * accelRate; i dont have targetSpeedVec and accel rate the targetspeed is the movespeed
when the compiler would figure it out anyway
then I guess you need to go calculate those variables.
I dont know what values to give them
accelRate is a value in kg/s. It is 1/(how many seconds it takes to go from 0 to targetSpeed). The kg scaling is because it applies this amount regardless of your mass.
if you want mass to matter, then it needs to be split off
Is it fine if i dont incluade mass?
that's up to you.
So if i dont want by mass so i dont need accelRate var?
imagine metal mario vs regular mario. When you move the control stick, const force means metal mario is slower.
ye
the way I coded accel rate means metal mario and regular mario move at equal rates
because my accel rate is kg/s, and not 1/s
But i mean i just want to move the player smooth on x axis and you told me addforce is better so there isnt simple way to do it?
But first i need to know how to do the 1 line right
no
idk who taught you this, or where you got this from, but you need to delete that mentality from your memory
do the process in steps, with however many lines of code each step requires
I mean i watched a lot of tutorails and all i saw use to use rb.velocity = new Vector2(moveSpeed * moveX, rb.velocity.y);
and how is that working for you?
Its not like in popular games
So what they add? are they adding acceleration?
- calculate your desired velocity
- calculate how fast you want to go to that velocity
- apply the change to get to that new velocity
Every popular game change the velocity by time?
you need to do what is right for your game
the code will only do what you tell it to do
Idk what is right its platformer and i want to make the controll feel good as possible
any process that does not include these 3 steps will likely not work for you
But movement with same velocity cant look good?
usually not, which is why we don't do that
So its like going from 0 to 4 movespeed with accelration and when stop from 4 to 0 with deaceleration?
thats what addforce do?
if (forceMode == ForceMode2D.Force) totalForce += force;
else rigidBody.velocity += force / rigidBody.mass;
}```
this is what AddForce looks like
and force mode at the end of the frame does: rigidBody.Velocity += totalForces * deltaTime / mass
But addforce wont just addforce infinitly i need to clamp it?
that is why we calculate the force based on the difference between the target vel and current vel.
The target vel is the max vel?
because we can do whatever we want to calcuate the target vel
K so i can do like cureent force max force and than do addforce till the current force reach max forch and than do rb.velocity?
target velocity is not the max. it is whatever we want our velocity to be, given infinite time at the current game state
AddForce in force mode should be done in FixedUpdate
public float maxSpeed = 5f; // Maximum speed
public float acceleration = 30f; // Acceleration
public float deceleration = 30f; // Decelerationfloat moveInput = Input.GetAxisRaw("Horizontal");
// Calculate target velocity and apply horizontal force
rb.AddForce(Vector2.right * moveInput * moveSpeed * acceleration, ForceMode2D.Force);
// Limit velocity and decelerate if no input
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
if (moveInput == 0f)
{
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, deceleration * Time.fixedDeltaTime),
rb.velocity.y
);
}``` this is a code i found is it a fine way to do accelration and decelration and use addforce like that?
that won't work
Why
AddForce modifies velocity at end of frame
right before physics sim
do what I told you
{
float moveInput = Input.GetAxisRaw("Horizontal");
// Calculate target velocity and apply horizontal force
rb.AddForce(Vector2.right * moveInput * moveSpeed * acceleration, ForceMode2D.Force);
// Limit velocity and decelerate if no input
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
if (moveInput == 0f)
{
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, deceleration * Time.fixedDeltaTime),
rb.velocity.y
);
}
}```
this. and on separate lines
Like how to know the desired velocity?
you calculate it based on whatever you want it to be
this is the velocity you want to be at if the player's input is constant, and you gave the game infinite time
like its 0 and go to 5 in 0.5 seconds? so the desired velocity is 1 in 0.1 second?
It would be like targetVelocity = 5 m/s. And accelRate = 0.5 kg/s. So from a current velocity of 0 m/s, we would be at 2.5 m/s after 1 sec, and at 5 m/s at 2 seconds, and 5 m/s at 3 seconds.
that is what the code I wrote does
// Calculate target velocity and apply horizontal force
rb.AddForce(Vector2.right * moveX * moveSpeed * acceleration, ForceMode2D.Force);
// Limit velocity and decelerate if no input
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
if (moveX == 0f)
{
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, deceleration * Time.fixedDeltaTime),
rb.velocity.y
);
} WHEN IM USING IT and dowing accle and deaccle like 75 the player moves fast and kinda smooth but i dont see accelration or deaccerlation like when i stop move it should still move a bit?
add force should always come last.
you only add force AFTER you know how much force to add. Do not add force, and try to correct it later
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);``` and this part needed?
i gtg now, but good luck
K ty for help
how does quaternion.euler work
did you check the docs?
m doing it rn n it's a lil confusing
like why doesn't it exceed 180 degrees
where are you seeing that Quaternion.Euler does not exceed 180 degrees?
also signed angles go from -180 to 180. unsigned angles go from 0 to 360
A single quaternion cannot represent a rotation exceeding 180 degrees in any direction.
again, where are you seeing this
thanks
the docs
fucking where
i think you are misunderstanding what that is actually saying. a quaternion can represent any rotation, they do not represent single angles. and they aren't even expressed in degrees anyway
what does that limitation mean
considering you won't need to construct quaternions manually and can just use euler angles it doesn't matter. just use euler angles and convert that to a quaternion using Quaternion.Euler
If you animate between two Quaternions, the object won't move by more than 180 degrees
I believe that's the point.
A Quaternion won't capture a 3600 degree rotation
If you lerp between two sets of Euler angles, you can go through many full rotations
rb.AddForce(Vector2.right * moveX * moveSpeed * acceleration, ForceMode2D.Force);
// Limit velocity and decelerate if no input
rb.velocity = new Vector2(
Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed),
rb.velocity.y
);
if (moveX == 0f)
{
rb.velocity = new Vector2(
Mathf.MoveTowards(rb.velocity.x, 0f, deceleration * Time.fixedDeltaTime),
rb.velocity.y
);
}``` this code is fine for 2d horizontal movement?
thanks Fen & boxfriend I think m getting it now
Looks fine to me
How do I get a randomization in C# Unity. was expecting there to be something built in but I can't find a random range function
can't find a random range function
it's like they didn't even bother googling that bit right there
public struct Blah
{
public string id;
public string name;
}
Blah blah = new();
blah = blahBlahBlahBlah;
blah.id = "blaaaaah";
blah.name = "uuuuuhhhhh";
will now blahBlahBlahBlah.id be equal to blah.id?
1 sec
I mean do I modify the source?
No
no. structs are passed by copy so blah = blahBlahBlahBlah; is just assigning a copy of it to your blah variable
I got into some strange problem where my SO skill is getting modified by the script and it's no bueno and I am trying to debug it and find out what causes it with no success... 😦
you'll want to learn about the difference between Value Types (like structs) and Reference Types (like classes)
anyone can help me how to install bolt in unity
wouldn't it just be done from the package manager like any other asset?
it's just called Visual Scripting now. and there's a whole server for it #763499475641172029
something I do with structs also modifies the source... dammit, broke my head already
Oh also I was thinking of Photon Bolt 😆
you'd have to show your code and explain what issue you're running into
facing error
oh that's also a possibility i guess lol. i just assumed they mean the old bolt that got turned into visual scripting 🤷♂️
wdym? Show screenshot/error message?
it will be a bit too much... I will spend some time modifying the code that made it all to go sideways and we will see... if no success, will come back here.
thank you
For April fools, they should make Vector3 a class instead of a struct
that might literally kill someone
ow wait... one question more
“It’s just a prank bro”
how did you install it
That looks like this asset https://assetstore.unity.com/packages/tools/visual-scripting/bolt-enhanced-186373
which is not the normal Bolt package
package manager then my assets then bolt enhance
Are you trying to install that
[System.Serializable]
public struct ActionSettings
{
public float TrueDamage;
public SkillType skillType;
public List<UnitStateMachine> endTargetList;
public int strikeCount;
public bool canCrit;
public bool isDodgeable;
public bool ignoreDefense;
public AffectedStat targetStat;
public bool isHeal;
public List<StatusEffectList> applyStatusEffects;
}
Basically my applyStatusEffects is getting polluted. I guess...
I guess I found the issue... here^
[System.Serializable]
public struct ActionSettings
{
public float TrueDamage;
public SkillType skillType;
public List<UnitStateMachine> endTargetList = new ();
public int strikeCount;
public bool canCrit;
public bool isDodgeable;
public bool ignoreDefense;
public AffectedStat targetStat;
public bool isHeal;
public List<StatusEffectList> applyStatusEffects = new ();
}
will that solve the issue? We will see in a minute
or the real Bolt package
what is StatusEffectList?
class
Unlikely the thing you did will fix anything
no i am trying to installl bolt to make games in unity using visual scripting
List is a reference type. so when you copy the struct it copies the reference to the List so each copy of that struct uses the same list
you installed some random asset store package
remove that
Go to Package Manager -> Unity Registry -> Visual Scripting
install that
(unless it's in your project already)
Visual Scripting is installed by default in new projects
Vector3 movementForce = ((Input.GetAxisRaw("Vertical") * transform.forward) + (Input.GetAxisRaw("Horizontal") * transform.right)).normalized * movementSpeed;
Debug.Log(movementForce);
movementForce = cameraTransform.TransformDirection(movementForce);
Debug.Log(movementForce);
rigidBody.AddForce(movementForce, ForceMode.Force);
Question. I dont understand how using the TransformDirection method magically makes you able to walk in the directions of the camera..
i just cant understand it
the TransformDirection method transforms the Vector3 you pass to it to be relative to the object's rotation
Imagine you ARE the camera. When you think of "right" and "forward" which ways do you look?
why doesnt the description of it say that..
That's what TransformDirection does
yeah but the GetAxisRaw stuff
id assume it works differently
those are just numbers
that you're plugging into a vector
and treating as local space vector
you then transform that vector into world space with TransformDirection
it does, just using different words. Transforms direction from local space to world space.
and now it's what you want
Although I will say
this code is BUSTED
Vector3 movementForce = ((Input.GetAxisRaw("Vertical") * transform.forward) + (Input.GetAxisRaw("Horizontal") * transform.right)).normalized * movementSpeed;
Debug.Log(movementForce);
movementForce = cameraTransform.TransformDirection(movementForce);```
transform.forward is a WORLD SPACE vector
you are passing it into TransformDirection which expects a LOCAL SPACE vector
so this won't work properly
it kinda does
kinda but not really
i mean
instead of transform.forward you should be using Vector3.forward
i dont know what its supposed to be
and Vector3.right instead of transform.right
yeah the transformdirection call isn't necessary. also those multiplications can be removed and use AddRelativeForce instead with the local space direction