#💻┃code-beginner
1 messages · Page 486 of 1
not sure im doing it correctly, i've created "Resources" folder in my "Assets" folder, then i've put the json files in it.
then in code:
string jsonString;
TextAsset jsonFile;
jsonFile = Resources.Load<TextAsset>("levels5.json");
jsonString = jsonFile.text;
and im getting object reference not set to an instance of an object
per the documentation you do not include the file extension
You probably need to make it an actual text asset.
Ah, I guess, a json file is fine too.
removing ".json" fixed it, thank you guys ❤️
....im stupid. the spawn points' box colliders were still onnnn 😭 here i was confused out of my mind when the solution was literally one button click. 
var emitParams = new ParticleSystem.EmitParams();
emitParams.position = (mousePos + Random.insideUnitCircle.normalized * 0.3f);
cosmicDustTap.Emit(emitParams, clickPower);```
if say my clickpower was 2 in this scenario the particles would just spawn in the same position so I wouldnt see them right
how can i check if my game is optomised when my pc is above average
so when i do bad code and such i may not notice since it wont strain mah system
player.position = Vector3.SmoothDamp(player.position, vehicleSeats[targetSeatIndex].seatPosition.position, ref positionVelocity, enterDuration);
player.localRotation = Quaternion.Slerp(player.localRotation, Quaternion.identity, enterDuration);```
how do i make the smootdamp and slerp run at the same speed?
so they both finish at the enterDuration
i need them to both finish at the same time
or will that do it?
Vector3 itemPosition = newItem.transform.position;
Quaternion itemRotation = newItem.transform.rotation;
newItem.transform.SetParent(targetTransform, false); // false ensures world position stays the same
ewItem.transform.localPosition = itemPosition;
newItem.transform.localRotation = itemRotation;```
This should create a **child** and bring it to its **parent** but still keep the `original location`.
The child moves to `another location` (not the original location) how can this be solved? 🤔
{
foreach(GameObject G in upgradeCardQueue)
{
Instantiate(G, panel.transform);
upgradeCardQueue.Remove(G);
}
}```
this is giving me errors however its working as intended am i good to ignore it
passing false to SetParent means it will not keep the current world position when the parent is assigned
https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
also you are using a world position to set a local position
you cannot modify a collection while iterating over it. you are not good to ignore these errors, in fact you'll find that it ends up not working the way you would expect when you have more than one object in the collection
i tested that I added 2 and it iterated over both of them
an exception will cause any code that should run after the exception to not run. so if an exception is thrown in the first iteration of the loop it won't reach the second
so then how did it
if you're just going to remove everything from the list, just use List.Clear after the loop
the smoothdamp is fps independent
player.position = Vector3.SmoothDamp(player.position, vehicleSeats[targetSeatIndex].targetExitPosition, ref positionVelocity, exitDuration);
player.rotation = Quaternion.Slerp(player.rotation, Quaternion.identity, exitDuration * 1.5f);```
but the slerp is fps dependent
how can i make it so that the slerp is fps independent and finishes at the same time as the smootdamp?
i am a COMPLETE beginer to unity and real coding in general can anyone tell me good tips and cways to learn atleast the basics?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
For support with non Unity coding you'd ask for assistance or suggestions from !csds (the c# discord server)
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
can that help me with learning c# cause i will be using unity
You'd ask or have your Unity related questions/discussions here and anything specific to c# in the c-sharp discord server.
You'll get more appropriate responses asking in the more appropriate server/channels.
ok
Reminder that Unity API (written in c#) isn't regular ol c# so you'll get better responses here in #💻┃code-beginner
Understanding packages is not the issue,
All I'm trying to figure out is when I make a grid, how do I make is so I can build on said grid
Asking Unity specific questions in the c# server could potentially have members redirecting you here as it's specific to Unity.
Well, there's no one answer to that. You need to implement it. So the answer would depend on how you decide to implement it.
What?
Yhea I know that, but I'm trying to find a good example that explains what's going on
One that dosen't have code pop out of nowhere
Or requires me that download something
What kind of code? Tutorials usually explain the relevant code. Otherwise there wouldn't be a point in them.
If you have a specific example, share it.
I don't have a specific example
All I'm asking for it be directed to a video or document just something that can tell/show me how to build on a grid
Like place buildings and stuff
The best we can do is google for you and share the link. But you can do that yourself, can you not?
Sounds like a thirty or so part tutorial.
Apparently I can since I can't find what I'm looking for
A thirty?
What makes you think that google would give us better results?
i would like to allow the player to edit the controlls in a menu and i need help with creating a variable that can be used in Input.GetKey(KeyCode.variableName) and i would like 1 script with every variable name like a dictionary so i was wandering how i would go about accessing that across diffrent scripts heres what i got rn
No I think cause people here are more experienced they'll know how to find better results
You can only get that much experience with googling.
Here's a quick google result:
https://www.youtube.com/watch?v=8kv1RcBKcqY
Does that help?
you can't change Keycode
if you want you can create Buttons
how about accessing the dictionary with another script?
whats the dictionary for? not sure i understand that part since input manager already does something similiar
to start with, in your keyDict script don't use string variables, use KeyCode variables. Then in your controller script you can use
Input.Getkey(keyDict.leftMove)
you could use a <int, Keycode> dict
Break down your problem into smaller steps and tackle them one by one. There might be a tutorial which explains exactly the system you want to make or (more probable) there might be not. If after thorough searching you can't find one which satisfies you, there probably isn't any that will. Find one which is similar enough to what you want to make, watch it, understand the general idea behind it and adjust to your own requirements.
just use the new input system 
2d or 3d
KeyCode is an int. It's an enum
and?
smth like this axis is
so why the dictionary?
lol no
2D
GetKey returns a bool
no
ok I forgot the []
int, enum[]
he could assign ints for every direction
but I doubt if this would be useful
no, I just don't see the point of using a Dictionary at all
i thought it would just be a simple option thats all
If he won't use the new input system, what could he do?
KeyCode leftMove = KeyCode.A;
Input.GetKey(leftMove);
Thus is just a, "Hey look what I did" video
aand how would i access this across scripts would it justy work?
This tutorial is really old but it could work? I followed this when I started Unity https://www.youtube.com/watch?v=ThGfVcMSUAY
Today, we tweak Grass and Dirt, and add Glass
@Niktu @gr4ss Indeed, the tuto forgot to tell me that, thank you very much!
hi can i ask a question here
ok this makes sense
stevesmith's idea works just as u wish
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
just have it all in one script?
No it's not. They pretty much explain how they implement the different aspects of the system. Then there's the project that you can download and research/use as a sample to build your own.
yea just make it static
emitParams.position = Random.insideUnitCircle * 7;
is there a way to make .insideUnitCircle have a minimum value so say the radius maximum is 1.0 but the minimum is 0.3 for example
and place it in some other script
or use singletons
use you can normalize it and then multiply by your desired range(or a random value in that range)
yo @teal viper can I ask you something?
Don't ask to ask
ok
anyway if u remember when u give me like an example of how diffrent enemy behavior should look like in my script it was something like this
I cant make the unit class abstract
because then I cant get it into the enemyLibrary array
Of course you can.
Wdym "clears"?
You should be able to drag in any prefabs that have components deriving from Unit
well I cant and idk why
Share your code and prefab setup
Well, then what did you try to drag into the array?.
You can't have Unit components, as they're abstract.
this is my unit script
Okay. And what do the prefabs have?
an example
the behavior script is empty tho
if I cant drag them as units what should I do
because its just makes sense for the enemies to be units
You need to implement the specific units first. Like GoblinUnit
That script would go on the prefab and not Unit
Then you will be able to assign it in the array as well
I dont get it
how would i make it so when the user clicks ona. button he can trhen click any key on hiskeyboard to rebinf the keybind
I need to create a new unit script for each enemy?
For each enemy type that you need different behavior for.
You. GoblinUnit would have all the same fields as Unit, as it's a derived class.
so I need to save the behaviour and the stats at the same script?
Yes.
so like I shoud create a game object then create a script for it and make it Unit : Goblin
and then write the stats and the behaviour there?
I mean, you can make it more complex, separate data and behavior and make it as complex as you want. But seeing how you have issues with even a simple setup like that, maybe don't overcomplicate it for now.
ye exactly
You probably already have prefabs for each enemy type. So you just need to write a script for each of them inheriting from Unit. And add the component to the prefab.
yes but now the prefabs are units which I cant drag into the array
Yes, well, they need not to have Unit script assigned. In fact, that's illegal if it's abstract.
so I need to remove the unit script and create a new script that inheriet from the unit script?
yes
ok i will try that and if I will have problems (and I will) I'll cry for help later
tnx though
{
var emitParams = new ParticleSystem.EmitParams();
for (int i = 0; i < CDPS; i++)
{
var randomDirection = Random.insideUnitCircle;
var randomDistance = Random.Range(3, 7);
emitParams.position = randomDirection * randomDistance;
cosmicDustTap.Emit(emitParams, 1);
dustCount += 1;
massCount.text = ((double)dustCount / SolarMassConversion).ToString() + " Solar Masses";
IncreaseStarSize();
float time = 1 / CDPS;
yield return new WaitForSeconds(time);
}
yield return null;
}```
im trying to spawn a particle in a random location based on particles a second which is the CDPS variable and im trying to make it look like they spawn 1 by one by delyaing it with the time float however I dont know what to put after the for loop as having nothing will lead to an infitine loop which unity wont run and having yield return null makes everything happen really fast and not in time
is CDPS an integer
yes, so integer divided by integer results in an integer. 1 divided by anything other than 1 is 0
that makes sense
There shouldn't be an infinite loop, unless you also increment CDPS every iteration.
no i dont
but it still gives me one
also i take it the higher CDPS is the less acuurate the timing will be cause of processing power?
you are still constrained to the timing of your framerate, so if CDPS is so high that the time it waits is less than the time it takes for one frame to pass, then you'll end up with fewer iterations of the loop than you would expect
yeah that makes sense
would the way around that be just doing everything that i do in the loop with a multiplier value to go past the frame rate limit
should i use smth like this i ehar sdomeone i think u mention the new input system
No idea, maybe use this? https://docs.unity3d.com/ScriptReference/Event-keyCode.html
I personally am not experienced with the new input system but if you can change the inputs through code, why not?
I'm not sure I get what you mean by that. But my typical recommendation to get around that restriction would be to use a manual timer rather than WaitForSeconds. So you just increment a variable by deltaTime each frame, then when it goes past your time threshold you perform the action(s) required and subtract the time threshold from it in a loop until it has gone below the threshold again. Kind of like this:
private float _timer;
private void Update()
{
_timer += Time.deltaTime;
while(_timer >= _waitTime)
{
_timer -= _waitTime;
DoAThing();
}
}
it will still be a bit inaccurate, but will accumulate those extra seconds caused by longer frame times so that it can still perform the expected number of actions in the expected time frame (or as near to it as you can possibly get)
Do you understand the problem?
Im beginner, sorry
Then you probably didn't copy it exactly?
you need to make it a method as stated in the error stack trace
or just use docs to find out your answer
yo dlich the ememy Units the inheriet from the Unit class shouldn't be abstarct too right?
Wat?
The derived classes shouldn't be abstract, no.
but when I create it as like:
public class GoblinUnit : Unit
{
}
I get compiler error
What error?
CS0534
'GoblinUnit' does not implement inherited abstract member Unit.Act()
ye I know just copied the error too
The error is pretty much self explanatory
i know
it tells you that you need to implement the Act method
but when I do inheriet it it wont go away
im not that stupid but its still wont go away
and then I get another warning
Then you don't inherit it correctly. Try opening the suggestions next to the underline. It should have a suggestion to implement the abstract class.
should I useo verried or something?
verried?
No. That's for overriding methods that are already implemented in the base class.
If it says that you didn't, then you didn't.
I guess I didn't then
Share the base class code.
the unit u mean?
Yes.
yes
Take a screenshot of your ide
in this one
Hmm... Maybe you do need the override keyword🤔
Yeah, you do need it. Confused with interfaces.
Anyways, next time just use the ide suggestion to autoimplement it.
You need to get into a habbit of sharing the error together with your question.
ye but I didn't change anything in the code
this isnt the script
dont you see the name is different
Whatever is on line 17 in BattleHudScript is null
You can't access an object when its null
when I click on it it doenst even send me to the battlehudscript tho
is your IDE configured correctly?
Should rely less on it sending you to the right file and more on reading the error details.
check external tools and maybe regen project files
also this what dlich said ^^
the link I sent you shows how to break down the stack trace
At some point you'll find that you'll need to dig into the stack trace to find the actual cause of the error.
ok just 1 more question
when I changed the array from Units to Scripts that inheriet from unit I needed to change the way I get the gameobjects from the array?
The array should still be Unit[]
That's the whole point. There's no point in changing it to the derived types.
so I have no idea what is the problem
I think the battlehuscript is null because whatever is in the enemyUnit is null
can you show what the line / script is its throwing null on
We need to see the actual code that throws the error...
here
you sent BattleSystem
thats the wrong script as I already explained to you
did you not read anything said lol
I did
thats why I said this
so why did you sent the wrong script again
the error tells you exactly which line threw the error in which script
but where it says and where it throws me is diffrent
doesn't matter, thats just unity being weird
read the actual errors thats all that matter
Did you read what I said about not relying on where it links you to?
nameText is null
ye I get that
so assign it
its null because TMP_Text is not assigned to a component
show
either its assigned properly and gets unassigned at runtime somehow, OR you have a copy with it unassigned
Name text is the first line that I make use in the enemyUnit information in the code
I think its null because enemyUnit is null
I just dont know why
are you passing a null then ?
I dont know why its null though
where do you call SetHUD
in the setup battle method in the battlesystem script
You can add a debug log in that method and see what exactly is being null
alr that makes more sense now why it was opening that..
should've read the whole stacktrace
I just try to understand why the enemyUnit is null
I changed the array to gameobjects that inheriet from unit
instead of Units
and then its became null
Because null is passed as an argument.
ur assigning a prefab
yes
you never actually instantiated a gameobject did you
umm no...
thats prob why its null
so where should I instantiate it
GameObject playerGO = Instantiate(playerPrefab, etcc.
same thing with enemyGo
if you assign the one from the inspector, whatever happens to that one in the inspector keeps getting cloned
eg if you destroyed it then everyone clones a null ref
or if its a prefab then you get weird behaviors because its not a clone but the same one, when you do = on a reference type unless you create a new instance you're passing around the same reference
I’m using a tweening library. There are methods such as move, rotate and scale. Should I have seperate scripts for each or have a single script where I decide which method to call with an enum, which one would be better performancewise
Unit playerUnit;
Unit enemyUnit;
GetComponent<Unit>(); do you have a Unit component on enemyPrefab
when is that run because enemyUnit = enemyGO; here is in Setup GameObject playerGO = playerPrefab;
at the started I did enemyGO = enemiesLibrary.enemiesLibrary[i];
I dont see anywhere you assigning a UNIT component to your enemy
and then enemyUnit = enemyGO
so what do I do here?
and how do I know there is anything there with Unit component
You need to start debugging instead of just making assumptions.
enemyGO = enemiesLibrary.enemiesLibrary[i];
I don't see any logging here so you're assuming this if statement even hits ?
or that it has the component ?
bool IsObjectInView(Camera cam, Transform obj)
{
count = 0;
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);
foreach (GameObject child in obj.GetChild(0))
{
if (GeometryUtility.TestPlanesAABB(planes, obj.GetChild(0).GetComponentInChildren<Collider>().bounds))
{
count += 1;
}
else continue;
}
if (count > 0)
{
return false;
}
else
{
return true;
}
}
and ideally when you found wat you're looking for you break out early from loop
you should know by now how to format code in this discord
i forgor
same thing
im trying to see if any of the child elements have a collider that are in the cameras view
bool IsObjectInView(Camera cam, Transform obj)
{
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);
return GeometryUtility.TestPlanesAABB(planes, obj.GetChild(0).GetComponentInChildren<Collider>().bounds);
}
}
!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.
this was the old version but only worked with the first collider
so the hand
i need to scan all the colliders
idk how
make an array
and scan through all of the children of your character
and grab their colliders
Hey guys, please help me with this problem:
I got playerData here (photo 1), but it don't equal to this data (photo 2). That's why I can't load my saved data
Wdym by "don't equal" what exactly is not equal?
I need 50, but i got 0
You don't need to share the same screenshots twice. That doesn't help.
Look on the comment
What type is it? Int?
yes
I know why it's equal 0, but I don't know resolution
Why is it equal 0?
As you can see, in arguments public PlayerData(Values values) I have my Values script. But this currencies in Values script is firstly template and after loading data my data
I don't understand what you mean by that. If values.Subscribers is 0, then debug why it is being 0.
look here
English! Do you speak it? Explain what you mean in words. We don't need to play a guessing game here...
well if multiplier is 0, it will always be 0
you are working with multiplication here
I got here 50, but I need to transfer it to my PlayerData script, where it is equal 0
don't worry about multiplyer
Where is it being equal to 50?
Is it serialized as 50?
It will equal 50 if I load the data
Ok, so it's not 0??
In load data script yes
but in playerData script it equal 0
So I need it equal 50
What is load data script..?
are you loading it?
https://gdl.space/ofenoleqig.cs can someone please explain why my player doesnt rotate on the y axis like it should with the yaw function?
I don't see load data script
I mean SaveSystem
gameObject.transform.position = new Vector3(700, 0, 0); im setting the transform of this object when i click on it however the transform is changine to 75000 something instead of what i set
is your object a child of something?
yes
use localposition
ah
Aight, here's what we're gonna do: you're gonna put a lot of verbose debug logs in your code and share the output in the console log. Until you can do that we have no freaking clue what you're trying to say.
looking for some feedback on this script https://pastebin.com/DGHZ0snG (too big for a discord embed).
Something in here is killing performance, specifically relating to opening/closing the door. While pressing the interact key on an unlocked door I get a momentary freeze. It's probably something simple which I just dont have a deep enough understanding of unity to see yet.
I'm also open to just general criticism. I rewrote this once already because the old version needed every kind of door to have its own script, so this is my first pass at consolidating. It might suck, feel free to tell me if it does (please tell me why it sucks so I can learn)
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.
You can't multiply a vector representing Euler angles with a Quaternion. That's not gonna provide the results that you expect.
i'm just gonna go ahead and assume it is this new int[999999999];
seems like it
I was explaining scope and memory allocation to someone and used that as an example. I have made myself a fool

lmao just randomly allocating over 3gb every few seconds when you press F
Noooo. Not like that.
Verbose logs. I have no freaking clue what these numbers represent. Add some text explaining that in the log.
I need 30 in playerData script
okay
ok but what can i do about it?
Rewrite the calculation. make sure it's correct. I'm not entirely sure what you're trying to calculate there.
Read about the difference between quaternions and Euler angles. They're not the same. They can't be used interchangeably.
And make sure you understand what type transform.rotation is.
Ok, now share the updated !code properly:
📃 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.
my raycasts aint working and ive got no clue why
never had this happen
UnityEngine.Vector3 targetDirection1 = playerBody.position - raycastPoint.position;
RaycastHit hit;
if (Physics.Raycast(gameObject.transform.position, targetDirection1, out hit, 20f))
{
active = true;
}
so it sends a raycast with 20 length out to the player
but even when theres literally a massive wall between the player and the enemy it still comes back true
wait im stupid as fuck hold on
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
how do i make raycasts visible again
Have a PlayerData field in your Values class. Assign the loaded player data to that field and use that everywhere you need, instead of creating new PlayerData every time.
Just like this?
well you need a Draw Ray or Draw line and gizmos to be enabled
where do i enable gizmos
I don't see PlayerData anywhere in that screenshot.
in the game view
Although no, it's not like that. I still have, in fact, the most important question, how to "assign" my saved values to template
Values class
{
private PlayerData playerData;
//Any method that you need access to player data
void Update()
{
someData = playerData.someData;
}
}
I need to create it in Values script?
so its going below me
I start feeling that you need to go learn some C# basics and the beginner pathways on unity learn.
What you mean, where I can made this?
Is there a quick way to disable both Intelicode and Co-pilot with like 1 or 2 settings? (not logging out or any other weird things)
using VS 2022 atm, not code
Because with your current understanding I'm not even sure that you're the one who wrote that code at this point.
The solution to you problem is very simple if you understand C# basics.
Anyways, I provided a tip here:
#💻┃code-beginner message
Let's see if you can use it.
I think it's won't help me, because my "playerData" don't have loaded data
When you load the data you assign it to that field. I think I already explained that.
Like its cool if it auto completes the word, function name for me but not suggest 10+ lines of code
You meaning like this?
You need to assign the player data on loading as I said many times now...
Which I did...
No you didn't
This is a different script and is unrelated to assigning playerData in your Values class.
I need to write this code is Values class?
Okay, what I need to make with this code?
Nothing. It's irrelevant at the moment.
Anyways, I'm off to sleep, but I suggest you do proper learning !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
well I debugged it and I know now for sure that the enemyUnit isn't null when I start the game and so are the enemyName, enemyLevel ect. and I still have no idea why I get an error
im having problem alligning my text with a object (in my case being a chest). i want to make it float on top of the chest but when i reset both position to 0 they are way too far apart. And the scale doesn't match too as my text appears ginormous while my chest is tiny. Is there any way to allign the text and the chest?
is it a UI text or a in game text
ui text
and how are you alligning it? and maybe try using in game text instead
i cant seem to find the function that puts ingame text. im on unity 2D
i think its under 3D, it should work in 2d also? unless maybe not i havent tried it
i see it. i was going under 2D thats why
thanks, now another problem is how to a allign it?
just change its position
that works. but i though there would be a intergrated tool that would allign both objects just like in blender
came in on the end of hte convo.. but maybe this would be something helpful for you..
if you make a gameobject and set it as the default parent.. then any gameobject you add afterwards will be created at it's position (0,0,0 locally ofc)
might be helpful to know for future things.. idk
i do this especially when im making world canvas because they start out soo big and are usually way off-center of the thing im adding it to... so i move my little gameobject into position and then create it
UI can't really align with game world objects without some code
You could use a world space canvas
Or you could use 3d game world text
Hey! How could I make a mouse sensivity slider?
With a UI Slider component
I have a coroutine where I want to check if any enemies are currently alive, and go to the next wave if there are not. Is there a good way to do this? I could do it in update but if possible I'd prefer to do it in the coroutine. I tried using a while-loop but found out the hard way that didn't work
why use either one?
define didnt work because that is the way to do it
You should have an event, enemies register themselves to enemy manager. When enemy dies it fires the event and removes itself from List on enemy manager, when list reaches 0 then you know they're all dead (check each time enemy removes from list)
Yeah I was just a bit dumb. I just needed to add a WaitForSeconds(0) in the while loop to prevent it from freezing the editor
wait.. j/k?
or
int enemiesAlive;
int EnemiesAlive { get {return enemiesAlive;}
set {enemiesAlive = valie;
if (enemiesAlive == 0) NextWave();
}}
void NextWave() { }
@celest flax
Hi, it's me again, sorry, I'm still following turorial for making a 2D videogame and I facing another problem : I tried to program a deathzone who redirects you to the PlayerSpawn area when you fall in it but instead my character just keep falling across. I did follow the programming and activated the IsTrigger case, put the Tag asked, but no result, Can someone help me? I'll put the link of the video (Warning : It's in French) https://youtu.be/5MmX3Mea29Y
Aujourd'hui on regarde comment ajouter des zones d'élimination dans nos niveaux. Cela nous permet notamment d'éliminer le joueur s'il tombe dans le vide ou se rend dans une zone inaccessible.
☕ Soutenir la chaîne ☕
➡️ sur Tipeee : https://www.tipeee.com/tuto-unity-fr
➡️ sur uTip : http://utip.io/tutounityfr
📥 Télécharger le projet de la série ...
you have to show your setup
also when you link a video you should link to the specific timestamp that sets this up
Sorry, here are the screenshots, I'm not sure which timestamps would fits the proper time but the creation of the Deathzone takes the first half of the video.
still looking for answer
bcs its not work for me
well the function would not work if you dont use the correct one
look at the video then compare what you got and let me know
You're setting its local position/rotation using a world position/rotation . . .
if i were to have an object that could instantiate many different kinds of objects, would i need to create a reference for every single object?
You only need to know what type of objects you want to instantiate (clone), assuming you mean instantiate mehtod from unity
like the prefabs right?
yea prefabs for example
would i need a reference to each prefab?
you could potentially use Resources and maybe use names , you still have to differentiate them somehow
having references to prefabs for each one in the inspector is the most straight forward way usually
it really depends on the project too tbh
If you need to keep track of them. Is storing them in a list not appropriate in your case?
im not sure if i know how to do that
okay
That's what I thought upon reading your message. You have to add a prefab to the List on spawn
[SerializeField] private GameObject objectPrefab;
private System.Collections.Generic.List<GameObject> _objects;
private void InstantiateObject()
{
GameObject newObject = Instantiate(objectPrefab);
// ...
_objects.Add(newObject);
}
I think their original question is they want to have different objects types to spawn
archer ninja astronaut
This has to be done with a single List and inheritance
ye thanks. it definitely works. @wintry quarry thanks thats what i ended up doing
Oh, It was OnTriggerEnter2D. I feel like a dummy... Thank You!
just so im straight, you mean you ended up using world ui objects?
well i went in 3d objects and clicked on text - textmeshpro
also
how do i get out of this thing? 😅
anyway as you can see
double click the Game word
i manage to allign the text with the chest so its fine
the one with the controller next to it
or hover the entire window and press Shift + Space
thats the quick way to mini-maxi every window
it worked!
looks good 👍
another thing that might save you some time.. is you can set the default Font of new text mesh pro elements
oh interesting. i will definitely apply it thanks
as well as a few other options.. but its really useful to just have it already set up to the font ur using for the majority of ur UI
boom.. no more Liberation w/e it is
now all i need to do is to make the pointer on the chest go up and down
DoTween 😉
pro-tip.. (dont use regular animations on your UI)
it'll force it to redraw all the time..
actually im not sure if that applies to the world canvases.. but even if it doesn't
using a tweening library is soo much easier / powerful to do little animations like that
by regular animation do you mean rigidbody.velocity?
no.. i mean the animation/animator windows
oh i was planning to actually move it up and down
w/ code?
yes
ohh yea thats the better route 👍
thats what DoTween does..
its just a library that already has all these premade functions
i see
like Bob, Shake, Twirl, Rotate, etc
those arent the actual method names.. but its just simple stuff
DOTween is the very first thing I install upon creating a new project. Animate your position, rotation and scale in a single line of code, with all the customization you could hope for... and that's only scratching the surface.
For the full documentation: http://dotween.demigiant.com/documentation.php
❤️ Become a Tarobro on Patreon: https://ww...
@bold iron just in case you want to look into it now or later ^ heres a decent run-down of it
ok, saved 👍
also, i have a question regarding my dashing ability. Is there a function that make your character go to point a to b with a certain speed instead of just teleporting it point a to point b?
are you using a Rigidbody2D for movement?
yes
you should avoid using translation at all then...
transform.position = blabla;
thats always teleporting.. you should instead use the physics methods to move the rigidbody..
rb.velocity = , rb.AddForce, rb.MovePosition, etc
oh, that was exactly what i did but it looked like teleportation
can you show the !code you have for your movement / dash
📃 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.
noo.. lol thats just an embed telling you how to properly share code in any of these channels
the links for example.. chose one.. (paste ur code into it and press the save icon)
the URL should then change..
just copy and paste that URL here.. and we'll be able to look at the code
ohhh, ive never used these tools sorry
no worries.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
looks correct from just that part
rb.velocity ur setting the velocity of the rigidbody..
that code doesn't actually teleport the rigidbody anywhere
so it just moves the rigid body?
so do i still need the iteration?
if u were to say use transform.position = newPosition; that would be a teleportation
(and also wouldn't respect collisions/physics
well the iteration im not sure about
Each iteration waits for 0.1 seconds before applying the velocity again, creating a staggered dashing effect..
i tried copying the code of dashing from other people but for some reason it doesn't work because each of them moves the player so fast i cant even see it. So eventually i decided to spend some time making my own dashing
ya, its fine to use translation/teleportation for stuff like that..
i only warn against using it for physics stuff
b/c ur bruteforcing it in a way..
u could literally walk thru a wall .. the rigidbody wouldnt stop u.. b/c ur teleporting ur way thru it for example
but for other things.. its a fine method
remember in situations like that.. it may be actually what u need.. just after fine-tuning the values ur using..
just b/c it doesn't appear to work correctly right out the gate.. doesnt mean its the wrong method
when building / prototyping i liek to use public variables and tweek them in the inspector as the game is running..
and hten once i find that sweet spot i jot down the new values and change them
oh so i might not have the correct variables for my rigid body
Well thank you for your input
I really appreciate that
for Dashing and stuff that has a timer, I usually use a Coroutine
using System.Collections; // Required for coroutines
private IEnumerator Dash(){
canWalk = false;
// Apply dash velocity
rb.velocity = new Vector2(DashDirection.x * 20, DashDirection.y * 20);
// Wait for the dash duration (e.g., 0.2 seconds)
yield return new WaitForSeconds(0.2f);
canWalk = true;
}``` to call: `StartCoroutine(Dash());`
*might be something else you can look into.. (Coroutines are really good to know regardless)
I see. So it will keep running rb.velocity for 0.2 seconds
it runs in order.. (it wont set the velocity twice only once)
after it does that tho.. it'll wait .02 seconds and then set ur canWalk to true..
(then ur walking/movement code should set the velocity back to whatever it needs to be)
no it just runs that code one time
and u can add yields anywhere thru-out the coroutine u want..
Ok
for example..
// do this instantly
// then wait a second
// then do this.
// now wait another second
// finally do this
ok
but wont the player look like it's teleporting?
Respected,
this will call on the particle collision....
if (_hit.collider.gameObject.name == gameObject.name)
{
UIController.instance.UpdateCurrentInteractingObject(objectName);
Debug.Log("why2: " + hit.textureCoord + "..." + hit.collider.gameObject);
// If the ray hits the object, returns the texture coordinates of the hit point.
return _hit.textureCoord;
}
this code works fine in the editor.
but when I export the android build..
it returns the default unity cube texture point correctly on collision... but on other meshes it print the name correctly and always return the (0,0) texture hit points on each part collision of the body.
I have applied my shader, but I think it's not relevant to the shader.
I don't know, I didn't get anything relevant to this..
And i am trying to get the solution from past two days.
Kindly guide.
Thanks
actually i will jjst try it again
why would it do that?
!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.
i will try it out.
what sir?
Please use that to format your code here
done
are you using a mesh collider on all such objects?
hit.textureCoord only works on MeshCollider
yes
!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.
i apply the mesh collider on all objects
im completely stumped with this, im trying to tilt a transform 45 degrees to the left or right if its close to its respective wall, but for some reason it only rotates in 1 direction regardless of where the wall is.
this is my code, onRW and onLW are booleans defined in another script to show if the player is near either the left wall or right wall, and rightN and leftN are the direction of the walls from a raycast (defined as rayHit.normal)
if(movescr.onRW && !movescr.onLW){
idk = Quaternion.AngleAxis(45f,movescr.rightN);
}
if(movescr.onLW && !movescr.onRW){
idk = Quaternion.AngleAxis(-45f,movescr.leftN);
}```
if anyone could please help id really appreciate it
where did movescr.rightN and movescr.leftN come from?
What do you do with idk?
SHow the rest of the code
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Tilemaps;
public class NewBehaviourScript : MonoBehaviour
{
public static GridBuildingSystem current;
public GridLayout gridLayout;
public Tilemap MainTilemap;
public Tilemap TempTilemap;
private static Dictionary<TileType, TileBase> tileBases = new Dictionary<TileType, TileBase>();
private Building temp;
private Vector3 prevPos;
#region Unity Methods
private void Awake()
{
current = this;
}
private void Start()
{
string tilePath = @"Tiles\";
tileBases.Add(TileType.Empty, null);
tileBases.Add(TileType.White, Resources.Load<TileBase>(path:tilePath + "white"));
tileBases.Add(TileType.Green, Resources.Load<TileBase>(path: tilePath + "green"));
tileBases.Add(TileType.Red, Resources.Load<TileBase>(path: tilePath + "red"));
}
private void Update()
{
if (!temp)
{
return;
}
if (Input.GetMouseButtonDown(0))
{
if (EventSystem.current.IsPointerOverGameObject(0))
{
return;
}
if (!temp.Placed)
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cellPos = gridLayout.LocalToCell(touchPos);
if (prevPos != cellPos)
{
temp.transform.localPosition = gridLayout.CellToLocalInterpolated(cellPos
+ new Vector3(.5f, .5f, .5f));
prevPos = cellPos;
}
}
}
}
#endregion
#region Tilemap Management
private static TileBase[] GetTilesBLock(BoundsInt area, Tilemap tilemap)
{
TileBase[] array = new TileBase[area.size.x * area.size.y * area.size.z];
int counter = 0;
foreach (var v in area.allPositionsWithin)
{
Vector3Int pos = new Vector3Int(v.x, v.y, 0);
array[counter] = tilemap.GetTile(pos);
counter++;
}
return array;
}
private static void SetTilesBLock(BoundsInt area, TileType type, Tilemap tilemap)
{
int size = area.size.x * area.size.y * area.size.z;
TileBase[] tileArray = new TileBase[size];
FillTiles(tileArray, type);
tilemap.SetTilesBlock(area, tileArray);
}
private static void FillTiles(TileBase[] arr, TileType type)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = tileBases[type];
}
}
#endregion
#region Bluiding Placement
public void InitializeWithBuilding(GameObject building)
{
temp = Instantiate(building, Vector3.zero, Quaternion.identity).GetComponent<Building>();
}
#endregion
}
public enum TileType
{
Empty,
White,
Green,
Red
}
im having an issue where its only placing at (0, 0) and it wont move, is there something off of what i did?
!code read it for long code blocks
📃 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.
as i said in the post, they both come from another script and are the direction of the walls from a raycast (defined as rayHit.normal)
idk though gets multiplied to the bodys rotation later like this body.rotation = Quaternion.Lerp(body.rotation,(gravityRot*bodyRot)*idk,0.01f+gswap);
Instantiate(building, Vector3.zero, Quaternion.identity).GetComponent<Building>();
assuming that by "it" refers to the building you are placing
showing the rest of the code would be better
yhea when i hit the button on the UI it places it
right so it's doing exactly what you told it to do
that part i understand,
im supposed to be able to move it at this point tho
And have you bothered debugging your conditions?
this lerp looks very questionable, did you get this code from somewhere? also its understood already that you're getting these values from elsewhere. we want to see where in order to actually help. right now you've basically just shown 3 completely random equations and said it doesnt work
void ThrowBall(int direction)
{
/* If direction = -1 => left
If direction = 1 => right */
_ballSpeed += 0.5f; // Increase the ball speed by 0.5 each time it hits the paddle.
float xVelocity = _ballSpeed * direction;
float yVelocity = _rb2D.velocity.y;
Vector2 ballVelocity = new Vector2(xVelocity, yVelocity);
_rb2D.velocity = ballVelocity;
}
hi, i'm trying to recreate the Pong game, but i have a problem with the ball movement, sometimes when the ball hits both paddles, it gets stuck in an infinite loop of bouncing (I added a physics material to the ball and set the bounce to 1). How can I solve this problem?
This is the function responsible for the movement of the ball
how could the ball hit both paddles in pong? Aren't they far away from one another?
yes they are
ive looked through and it doesnt seem to deviate from what im following
can you explain what you mean then?
I will try to record a video
add a slight angle offset when it gets stuck like that, if I understood it keeps hitting back n forth the same direction?
Yes that's exactly what I'm trying to say
float xVelocity = _ballSpeed * direction;
float yVelocity = _rb2D.velocity.y + angleOffset;
Vector2 ballVelocity = new Vector2(xVelocity, yVelocity);
_rb2D.velocity = ballVelocity;
}
i recall just basically giving the ball a slight "nudge" when it goes like that
like this?
What value should I give the angle offset?
between -5f and 5f?
maybe I'd do
Vector3 reflectedVelocity = Vector3.Reflect(ballVelocity, paddleNormal);
if (Mathf.Abs(reflectedVelocity.y) < 0.1f){
reflectedVelocity.y += 0.1f * Mathf.Sign(reflectedVelocity.y == 0 ? 1 : reflectedVelocity.y);
}
ballVelocity = reflectedVelocity.normalized * speed;
I dont use physics materials usually esp with velocity, much better to use Reflect method imo
obv replace the magic number for the offset
i did add a physics material to the ball with a bounciness of 1, so this won't meet the game requirements?
should i remove it?
you can leave it if you want, depends on your game
could you explain to me what this code does? because I am a beginner
if (Mathf.Abs(reflectedVelocity.y) < 0.1f)
checking if the direction "reflected" from ball hitting paddel (the bounced velocity) .y is close to 0
meaning "too horizontal" so add a slight offset
Mathf.Sign is very simple
I appreciate your help
did it work ok ?
actually would prob replace == 0 with < or mathf. approx
private void Update()
{
if (!temp)
{
return;
}
if (Input.GetMouseButtonDown(0))
{
if (EventSystem.current.IsPointerOverGameObject(0))
{
return;
}
if (!temp.Placed)
{
Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cellPos = gridLayout.LocalToCell(touchPos);
if (prevPos != cellPos)
{
temp.transform.localPosition = gridLayout.CellToLocalInterpolated(cellPos
+ new Vector3(.5f, .5f, 0f));
prevPos = cellPos;
}
}
}
}
this part is supposed to make it moveable
I'm modifying my code now, I'll let you know
physics materials are nerfed imo.
I just get weird inconsistent results sometimes
i usually end up needing to use 2 materials and being very critical when tuning the values to get my results
i need to start using reflect more often
ya, same
i first used it on bouncing raycast bullets 😈
like a physics material w/ bounciness of 1 should be a perpetual motion machine
but thats usually not the case
i always think Lasers and Mirrors lol
i was once working on a thrid personm game based on lanterns and colors
where ud have to mix certain lights to open certain doors
i was doing a video / tut on it but kinda got lazy lol
relied alot of color blending
Hey, is it okay to use System.Activator.CreateInstance to create a instance of a class you want to use.
Like i've got a Consumable class
that has a ConsumeEffect variable for what it effect it has when used.
With each unique effect being a child class of the ConsumeEffect class.
Only problem is that I cant assign that script to the variable without creating an instance of it; so that'd mean creating an instance manually for every new consume effect and assigning it manually.
So instead; I thought of just passing in the name as a variable, and using the name to create an instance of the class. But I don't know if thats safe or proper.
So i want to add some footsteps into my code, and i have an idea of how to do so but i have no clue how to actually do it. I have 5 different sfx which i wanna change the frequency of and pitch of, depending on if im walking crouching or sprinting.
(This is the movement code)
If these things are MonoBehaviours, no it's not ok.
If they're monobehaviours you can use a prefab and instantiate it
or well the ConsumeEffect is a regular class.
that was my second idea.
was gonna have like a get_effect method in the consumeEffect class that would return the specific class needed.
I might do the second one just because it sounds a bit safer.
i was wondering if thats how raycast bullet bouncing worked, could you also shoot a raycast to the ground and calculate the angle between the ground and the raycast and if it is higher than a specific threshold then dont bounce, but if its lower than spawn another raycast at the raycast hit position with the appropriate angle and length?
i feel like thats way more complicated than vector3.reflect 😅
would just Vector3.reflect, and calcualte the angle between the 2 to decide if i want to od the next cast or not
V3 reflect simplifies everything in terms of just finding the direction
either do decent amount of trig or use reflect, is no brainier lol
i guess it seems mine is way more complicated than it has to be
also its not that much math
is a very "simple" function too
public static Vector3 Reflect(Vector3 inDirection, Vector3 inNormal)
{
float num = -2f * Dot(inNormal, inDirection);
return new Vector3(num * inNormal.x + inDirection.x, num * inNormal.y + inDirection.y, num * inNormal.z + inDirection.z);
}```
reflect is very simple
yup
can anyone smarter than me help with this...
what's the current issue you're having with it?
You can either check the velocity or WASD and just play the looping sound?
I simply dont know how add the stuff, like i can understand the logic but i just dont know enough about code to apply it. Ive searched some tutorials but they are either very outdated, or have notable jank.
Unity has footsteps example in one of their Starter Assets, its worht checking out
iirc they use Sin function
https://www.youtube.com/watch?v=_cCGBMmMOFw&list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw&ab_channel=SebastianLague this guy helped me out with that..
figure out how to piece together code.. how it works structurally and then after that makes sense its just google for help.. and then directly looking up documentation and "seeing thru" the jank in tutorials to figure out what the important bits are
then ofc. the pinned comments
Uh, gotcha.
wow the old first person controller in Standard Assets used custom tick to help with playing footsteps based on traveled distance
https://github.com/Unity-Technologies/Standard-Assets-Characters/blob/master/Assets/_Standard Assets/Characters/Scripts/FirstPerson/FirstPersonBrain.cs#L318
let me check that out
ehh the new one is probably better
if you're new w code it might be too complex, seems over engineered
Yeah kinda, i was really hoping to try and build it off of my state machine (Which i got from following a first person controller guide)
the concept is more or less the same, check the distance traveled and compare numbers. Its pretty much a math problem
Would it be less complex to do a timer between steps multiplied by a float (for whether its more or less frequent) and then see if still moving? thats kinda the idea im tryna implement
a timer could work but it will be jank
if you want a proper result you should count distance/steps
would just do it on distnace traveled
something like footstepDistanceCounter += characterVelocity.magnitude * Time.deltaTime;
float chosenFootstepSFXFrequency = (isSprinting ? footstepSFXFrequencyWhileSprinting : footstepSFXFrequency);
if (footstepDistanceCounter >= 1f / chosenFootstepSFXFrequency)
{
footstepDistanceCounter = 0f;
audioSource.PlayOneShot(footstepSFX);
}```
had this in my old code
i have always done it with distance, or if i have a animation use events in the animation
There really aint an easy way to do this sadly ;-;
yeah def animation events soo much easier when you have real legs
events would be the easiest
what was just posted is the easy way
would animation events work even if i dont have animation? (Just using a capsule)
there would be no point
it can but you mind as well make a timer at that point
just use the distance approach then
yeah go for distance
i use it with animation events so it syncs perfectly with what people see
ah
if you do not have the animation use the distance
would take less time to implement then the amont of time we talked about it
Ok my minds getting pretty liquid, let me try and figure out the distance thing and circle back if im truly stuck
well im not entirely sure how to just smash that in my current code
if i could i would, trust me
its literally just getting the length of your velocity vector adding it to a field every frame and when its above a threashold you reset it to zero and play the sound
Clearly i dont know how to do that man, im tryna learn that crap mind you
if you do not have a rigidbody providing velocity you can also just compute it by subtracting the positions between last frame and current frame
Well i have an empty object titled "Orientation" which i use for position, i have it referenced in my movement script and if i can figure it out my footstep script
you have rb already
use its velocity as shown
Idk man, i was just following the tutorial the dude provided (except he didnt provide audio apparently)
Its just a first person movement tutorial from some youtuber named "dave", its covered slopes, crouching, walking/running, but NOT audio
alr well its pretty much as simple as the code I sent to get something going, just put it inside a Grounded check (update or fixedUpdate in this case) and while movement > 0
the audio could literally just be its own script though just give it access to the rigibody to get velocity, and give it a way to know if you are on the ground or not
Thats what i am tryna do currently, obviously with little success
i have the orientation already linked to the footstep code, actively trying to deduce the distance thing
why not describe what part you're having trouble with
Specifically how to find when ive passed a certain distance, and then play the audio. I can worry about pitch and random sfx later
the code to do that was posted above
just use .distance and then compare it to whatever
its just adding it to a variable per frame then in a if statement checking if its greater then a given value
thats what we store in the variable
to keep track of it
should i make a float named like distance or smtn?
^ yes they're all pretty much floats
if you dont have sprint you can simplify it without the ternary ( ? : ) part
you basically need 2 in the inspector (1 if you dont have sprint)
[SerializeField] float footstepSFXFrequency = 0.3f //say 0.3f or something to test
i have a sprint, but wouldnt it not matter if its distance based? same for crouching, no?
well it matter because your footsteps would be more frequency if you run, walk/crouch slow/ etc. 😛
read the code, it was only checking it to decide what sound to use
well there example was changing it, but for hte most part moving faster will make faster footsteps already
And not to be a broken record (really do appreciate the patience) but how do i increase my distance float based on my movement? Still fuzzy on how to actually increase based on the movement
something like footstepDistanceCounter += rb.velocity.magnitude * Time.deltaTime; for example
K lemme try that, lyk how that goes
remember footstepDistanceCounter is a private field that resets every time threshold reached
currently still trying to get the darn thing to increase, current issue is it doesnt have a RB (its in a seperate script, should i move to my controller?)
just reference the movement script and make some public vars/props read only for now
this way you can also pass the Grounded bool
Ok its scuffed but i THINK its fine (Taking a SS now)
bool grounded;
public bool Grounded => grounded;```
same as this btw
```cs
public bool Grounded
{
get { return grounded; }
}```
if(movementScript.Grounded && etc..)
In my code i have a public Rigidbody rb;
and then also '''cs void Update()
{
distance += rb.velocity.magnitude * Time.deltaTime;
}'''
well that didnt fricking work, you get the idea
The thing is increasing, and im happy
well you're increasing it, thats good
you never use it though
huh
also you need grounded, dont increase it if you're not on the floor lol
oh right
also you probably only want to increase it if movement input > 0
lemme just move this to my main move script, easier for me
its probably cleaner later on to do it as you're doing it now
all you need is to reference it as shown then expose each thing you need from it
btw distance is not something you should expose in the inspector, this value should not be changed by you at all. only via code
right right, currently i have it that way just to see if its working
also; got it to increase only while grounded (this was much easier as its already got the grounded params in the main code)
let me make a thing so it resets when it hits a certain float (for now ill do like 2 because my man moves quick)
but it would be just easy to just grab it from other script..
its 1 line
idk man ;-;
accessing members in other scripts is something very important you're gonna be doing 70% of your time
right, also managed to get the reset working
you're inadvertently already doing that when doing any . operation
oh neat, if it wasnt insanely obvious im very new to this stuff
This is what i did:
if (distance >= stepLength)
distance = 0;
and its working like a charm
rb.drag = groundDrag; rigidbody is already a component / script you're accessing its public property drag
For some reason the dude that did my code made his own groundDrag
because drag acts different in air
huh, for now it works so id rather not tinker with it however.
But i do see why its better
i was just showing an example of how you're already accessing members in other scripts
doing it from your own is no different
ah right, gotcha 👌
So wouldnt i just play an audio in the reset code?
because it will only play once, i believe

lmao nice, that being said no clue how to do audio ;-;
^ its literally in the example code too
looks like you actually missed a step
ya, #💻┃code-beginner message like this
wat would that be..?
you have to reference an audiosource
does that work for multiple audios?
look at the if statement
you can shuffle thru clips..
PlayOneShot takes a clip
u can change that parameter thru code whenever u call it
i see... lemme google what an audio source is :c
AudioSource -> Radio
AudioClip -> The Music
oh i see, can i attach multiple clips, or would i need 5 audio sources 💀
you can swap them
but if they are meant to play at same time then you probably want multiple sound sources
nah, they hopefully dont play at the same time
and how would i swap them, not manually
the assignment operator =
(also once again huge thanks)
or with PlayOneShot you can just pass a different clip (you only need as.clip = for .Play)
[SerializeField] private AudioClip jumpSound, hurtSound;
as.PlayOneShot(jumpSound)
as.PlayOneShot(hurtSound)
the thing is say there aint no overload method for play oneshot
i copied what spawn camp put
you should probably do a c# course 😅
With my spare change :<
but the thing has a dang clip in the inspector???
play one shot sets a new clip and plays it once
a method signature we're talking about here @torpid snow
that is why it wants a clip as the arg
just have your script reference the clip you want to use so it can be passed to PlayOneShot
b r u h
its affectively dragging a clip into that slot for u, playing it, and then continuing doing audio source stuff
the PlayOneShot method has nothing to do with the audio clip assigned in the inspector on the AudioSource. It is used to allow an AudioSource to play more than one clip at a time (or to more easily change which clip you want to play such as in your case)
you can set the clip urself and then use other methods to play it.. but OneShot is just the right tool for the right job most times (imo)
the one assigned in the audiosource clip section in inspector only works with Play()
i am absolutely clueless right now
start testing stuff
good idea
find an audioclip and go hamm 🥩
try stuff and read docs for the things you are uisng
yup best way to learn is experiment, consult manual repeat
For now play works fine
I’ll fig that stuff later, gotta go :/ also huge thanks once again!!!!!!
Play has its flaws, for example it cancels the previous sound
(if you have not enough spacing between the two it stops the first one from playing)
Oh
since it has PlayOnAwake u could for simplicities sake say.. have 3 gameobjects each Named a different Sound.. put an audiosource on each.. and then put a specific clip into each slot of the audiosources.. then u could enable a gameobject and it'll just play a sound.. and then disable it so on and so forth..
buuut... the shorter way to do all that.. is reference the audiosource and call OneShot on it
thats way more complicated then just play one shot
lol.. exactly
since you would need to check for the sounding ending
nah, ud disable and enable.. (once it ends it ends)
Yeah, once I get back I’m gonna try and learn one shot. It sounds simple but I just don’t know how to do it currently
then when u ready to play it again.. u disable and enable
rinse and repeat.. but yea.
not relevant.. just use OneShot.. lol
Lmao, right.
One shot allows for stuff like random pitch? Or would I need a separate stuff for that
its realllly simple... [audiosourcereference].PlayOneShot([audioclipreference]);
I screenshotted that, have to try that.
full script being just
public class AudioManager : MonoBehaviour
{
public AudioSource bassButtonDropSource;
public AudioClip bassButtonDropClip;
public void PlayBassDrop()
{
bassButtonDropSource.PlayOneShot(bassButtonDropClip);
}
}```
you just adjust the pitch before playing it
no thats done on the AudioSource
thats why sometimes having multiple audiosources for different scope is okay
This may be ambitious but could I do it off of my current speed to pitch? (Fast speed high pitch, low speed low pitch?
suur
would be fairly easy
your imagination is your limit
u could even remap it.. set high and low range
That seems like another can of worms for me though lmao
it is..
welcome to the rabbit hole
another can, another feature
I miss scratch…
once you get used to a full programming langauge, it will feel a lot better
I got all the logic, just not the knowledge. Like a storyteller who can’t write lol
its a skill just takes some time and practice to get the hang of things
like going to foreign country , can't expect to know the native tongue right away lol
Half of coding is just persisting through the urge to quit, it feels
but u cant pack this much data juiciness on a scratch window
i made a game in scratch after learning unity
it was awful experience
its really no different then any other skill to learn you just have to give it time and practice and do it
Lmao, sounds fun
I made ONE game on scratch and it’s my magnum opus
Truly a spectacle of computers
Anywho thanks again for all the help, and sorry for eating y’all’s time!
Imma try and find out about one shot
!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.
private IEnumerator motion(){
transform.Translate(Vector2.up*Time.deltaTime);
yield return new WaitForSeconds(2);
transform.Translate(Vector2.down*Time.deltaTime);
yield return new WaitForSeconds(2);
}
ive tried to make something that would make a object go up and down. Does anyone recognize anything wrong here? As the object will start going up very fast and stop. After it would move up and down at a very inconsistant rate/
ive made a theory that Vector.up make it so that the object goes to the original postition similar to 0,0,0 but with a digit change on the y axes tho i have no idea why it twiches
This code will go up for one frame a tiny amount, then do nothing for two seconds, then go down for one frame a tiny amount, then do nothing for two seconds
oh
Basically - it's doing exactly what you wrote
i mean, thats how coding works lol.
Indeed
for some reason waitforseconds function doesn't stop the code. my timescale is at 1 too
grid = new Grid<GridObjects>(gridWidth, gridHeight, cellSize, Vector3.zero, (Grid<GridObject>g, int x, int y) => new GridObject(g, x, y));
^(15,103)
Assets\GridMap\Scripts\Testing.cs(15,103): error CS1678: Parameter 1 is declared as type 'Grid<Testing.GridObject>' but should be 'Grid<GridObjects>'
this error messege aint making sence
It will pause the code for two seconds
How many times are you starting the Coroutine?
Seems pretty clear
You put the wrong type as the first parameter in your lambda
it actually stops the code's coroutine but doesn't stop the whole code. What i did was introduce a cooldown system the same i did for my dashing skill. Now it works but im still trying to find why it codes up a lot at the start of the code.
the coroutine started each frame, thats why it was so inconsistent
what??
its saying it should be 'Grid<GridObjects>' when it is
(Grid<GridObject>g
it clearly isnt
Look closer
how descriptive. are you using AI to code or something?
no
https://www.youtube.com/watch?v=dulosHPl82A&t=101s
this is what ive been following
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=dulosHPl82A
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
✅ In this Unity Tutorial, let's make an Awesome Grid Building S...
you copied the code wrong then, look closer and follow it exactly
im surprised code monkey used such code for whats meant to be beginner friendly tutorials. i asked about if you used AI cause using lambdas like that is not beginner friendly at all
i made sure it was right, even going letter by letter
well look pixel by pixel then. i see a clear difference and it took 30 seconds to find it
notice no plural on theirs
tbh you should just write it exactly using the same names. Even changing stuff like GridXZ to Grid makes it harder to find errors
hi guys. im trying to make this basic twin stick controller and seem to be stuck. I've got the general movement of the character down and it works pretty well. The issue I'm having is both getting the controller to detect when a gamepad is in use and getting the right stick to rotate the model. the script appears to be doing so, but nothing actually happens when i switch to a gamepad besides being able to move the character around. Any help is appreciated
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.
is there a way that i can acces all the trees individualy that i spawned in with mass place?
Why is this groundlayer pop up is showing something else instead of list of layers.
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.
it is showing the layers . . .
oh, ok I was looking for tags
sry
click the Layers drop-down up top and you'll see they're the same . . .
oh, okay . . .
I know I know... Didn't notice the difference between layer and tag.
What is the difference between layer and tag?
layers involve the physics engine; they determine which GameObjects interact (collide) with another . . .
is there a way that i can acces all the trees individualy that i spawned in with mass place?
tags are simply attached to a GameObject to help find\search for it . . .
What does "mass place" mean?
As opposed to?
just directly calling the gameobject
Presumably they're doing something other than calling SetActive
Which is part of GameObject
thank you, because ive seen multiple people trying to directly changing the game object with the GetComponent which gave my a error each time i do it
i wanna spawn destinations for ai in a grid around my terrain, my terrain is very big, is there a way to do this so it also sit on the terrain and not under the terrain?
You can sample the terrain or Raycast against the terrain collider
idk what that is, im realy new to unity
Time to Google it
looks like im the one that didn't remember correctly. thanks
im still a bit confused, i have tried reaserching but cant find anything
sorry to be pushy but i really need some help
@rich adder you beautiful son of a gun! Got it working perfectly, random pitch, random sfx and all. It truly puts a tear to my eye
