#💻┃code-beginner
1 messages · Page 263 of 1
no such thing as good "Ai" its all crap search engine results mashed together + some babbling
What type is Sound.AttackFlesh?
Hello! I have a question. I have a wall that should be touchable from all directions, but the touch should be directed from some distance, so I inflated the collider. The green cube should follow the hand, which it does perfectly only in two rotations around Y axis at 0 and 180 degrees. I'm definitely handling the rotation wrong, but can't figure out how to do it right. How to do this right? Thank in advance!
yeah but this one has more for coding
Is there a way I can put a collection in an enum?
so it is nice
Well also one thing to consider is, since you dont know the basics, you are gonna need a entirely premade system. Not one that you code with, because you wont know how. Those are definitely gonna be expensive IF you find one u need.
Make a list
and it taught you nothing lol
I give questions and it answes
so I get to undestand why I do something
but not how
so useful for understanding where and what to put
and more useful when I actually learn
Probably a good spot to use Dictionary , use enum as Key and make audioclip the Value
Oh u meant you use ai to code. I meant AI like a automated character in the game
yeah
I mean rn that's the best chance I have
and ofc watching yt
but both is crucial rn
You could also, like, learn things
No, your best chance is to ask your teacher for advice on what you can do. Maybe get an extension and ask them what kind of game can be reasonably done
and I spend a lot of time
yeah well pal this is bigger then just a game project
so I am kinda screwed
Probably should have started 51 days ago then when you had the chance
yuh should have
but here I am
learning as much as possible in a really short time
and getting codes from ai
You really dont wanan end up like half the people in here who use AI. With systems they dont understand, which doesnt work, and then they try to fix a system which was flawed from the start.
Sure, itll do the absolute basics correctly, but when it gives you a hammer instead of a saw, you wont know the difference. Then you'll be stuck wondering why you cant cut anything with a hammer
Anyways, AI code isnt allowed in here so you also likely wont be getting help if you choose to continue with it.
Is this right?
I've done everything it said here it still doesn't work.
Have you put anything in the list?
(0, AttackFlesh.Count)
But your list is empty friend
No, I haven't worked with enums much. I wasn't sure if any of the values I put in the original enum were carried over once I made a new list.
like what exactly ? and which editor are you using

This has nothing to do with enums, you just made an empty list
Yeah I know, I try watching yt first and find scripts that may work, bc I really want to learn but rn isn't really the time to learn 23124125 hours of coding
Got it.
Studio, added the unity add-on(idk how it's called), and updated everything.
you just need the basics, once you know. that everything else makes a bit more sense
Studio? they're both have studio in the name
purple one
do you recommend any good basics introductions?
I've found some
try regen project settings
but don't really know what is best
thx
thx bruh
I think this is right.
made it worse
Uh, how are you intending to get the xth element of AttackFlesh to add to AttackFlesh
If you had it in that list, why would you need to add it to the list
is old videos like up to date or is it harder to understand
I don't understand. The list started off empty, but I'm not supposed to add to the list?
same concepts..
alr
the basics of c# doesnt change
You are supposed to add to the list. Right now you're trying to add things from the list to the list which makes no sense
What is the hand object, is this some UI object? You may be able to raycast from the camera and get the actual point
just figured out how to solve a system of equations with a matrix lol
i really should not have dropped out of college
yo i followed this tutorial on data saving and we were printing an error when we can't find save file and it prints for me so how to fix this?
https://www.youtube.com/watch?v=XOjd_qU2Ido&t=957s
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void SavePlayer(DataGroup player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.fun";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "/player.fun";
if(File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}
Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.
● Easy Save: https://bit.ly/2BzgdXb
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·····················································...
What error
Then that file doesn't exist
so how to create it?
Save once first. The code that saves the file will create it if it's not there
Also this
As per the FileMode.Create argument.
But also I wish this video did not exist since they use the BinaryFormatter which has security vulnerabilities
Consider using another means of serializing your data, like with JSON
I'm not ready to jump into Dictionary with this quite yet. I'd like to figure out what I'm doing wrong. I thought the goal to be able to pass AttackFlesh[i] to the method was to add AttackFlesh1, AttackFlesh2, AttackFlesh3, and AttackFlesh4 to the AttackFlesh list. Based on what digiholic said it sounds like that's either not the case and/or I'm doing it wrong.
If you want to add those to the list, you need to actually add those to the list
The hand is just a kinematic rigid object at the moment. I have a problem with the spatial relations. I was thinking about raycast and another collider, but there are other limitations for the green object's position on top. Now I am thinking that maybe I can use the Transform's right and forward vectors that should rotate together maybe... after the changes of the basic code between different versions of Unity - I have hard time figuring out what holds and what doesn't.
Think of it this way: You have a shoebox. The shoebox can fit two shoes in it, but right now it's just a box. On the table next to you are two shoes. You then take a shoe out of the box and put it in the box. The shoes on the table are untouched. Does this make sense?
Yes.
Then I cannot help you
Now I'm just trying to figure out how to get the shoes on the table in the box.
I think I see the problem.
Programming deals with logic and rules. If you don't even understand basic reality to the point that the scenario provided makes sense, it will be impossible to help
You pick up the shoe, and add it to the box.
Just like if you want to add something to a list, you add that thing to the list
You don't add an element of the list to itself
I understand now, I didn't realize I put the list back into the Add section.
I am working on trying to add the enum into the add section instead of the list itself.
Enums aren't really collections, so you can't use [i] to access specific elements.
This means "The object from the AttackFlesh list at index x"
What is an "add section" of a list?
A list is a list
it doesn't have sections
it starts empty. Things don't exist inside it until you Add them
The parameter to Add is the thing you want to add to the list
i think he just means the .Add function
If you want to add one of your enums to the list, add that to the list
Yeah, I've looped back to the same original problem. (Image 1)
I can make it work if I do it this way though, but not as ideal. (Image 2)
Again, Sound.AttackFlesh is not a list
Why are you trying to index it like a list
And the second image is what you should be doing
that's the solution
Just change your random range
#💻┃code-beginner message
without dictionaries
It took this long to explain that you cannot add a list to itself I don't want to explain dictionaries
Oh, but I need to get rid of the for loop now.
Ok but what if he used Enum.GetValues(typeof(Sound)) and iterated over that. 🙃
yes they can do that certainly
Tried with the forward and right - they are not normalized, but messed up because of the scaling of the parent object (the wall). And then it's all local scale... but the hand is in global. Urgh.
I think I have what I need. I'll work more with dictionaries in the future, but for now I'll be avoiding unless I run into a situation where it's required, or once I'm more comfortable with lists. Thanks digiholic.
Real problem here is this that enums aren't good for this scenario. Some type of string ID to AudioClip dictionary would be best, but even that is likely overdoing it.
@austere hedge What's your goal exactly? Do you just want to play a random sound?
My goal is to keep all sounds within a Sound Manager so I don't have to add an audio source for every single sound. Some of those sounds I want to play from a selection of random sounds instead, so in the example of AttackFlesh I want it to make a different attack sound each time an attack happens. So some sound effects are random, others are always the same.
You could just make a list of AudioClips and then play a random one without needing an enum at all
A list with only one clip in it means that clip is the only one that can be rolled
Do you just have one audio source on the SoundManager?
The tutorial video that I went through on how to create a sound manager utilizes enums, so that's why I have been using them.
enum can be useful to know which sound type/audioclip to play
Yes, it's a temporary sound source that gets destroyed after its played.
not storing sounds
Oh so you instantiate a gameobject with an AudioSource, it plays the sound, and then gets destroyed?
Yes.
Do you do all of that manually or do you use PlayClipAtPoint?
I figured in the long term it would help to use enums if there's eventually a ton of sound effects. I think it would make it easier to keep track of.
It's sort of the other way around. Enums get a bit unruly when there's many of them.
How is the hand controlled though? Because if it's by the screen space (user is dragging it around) then the whole setup is probably a lot harder than needs to be
I started with PlayClipAtPoint originally, but if I remember correctly the issue I ran into was I wasn't able to set all the properties if I do it that way. At least that's what I remember. So I'm currently doing it as a manual solution so I have full control.
much easier to have an audiosource live in ur scene.. change out the clip and play it
list of audioclips is the most modular and expansive way
imagine a neat buckets you can throw your sounds in
it holds chars which can be anything in UTF-16
If I have it working the way it is right now, by creating and destroying GameObjects with sounds attached to them, is there any advantage to me doing it the way you suggested?
yes.. creating and destroying over and over is bad for performance
Modular is what I'm looking for. I don't have that many sound effects right now but the whole reason for me going down the sound manager road is because I want to make sure it's as convenient as possible once the project gets larger.
a sound manager is good idea. Just go with the list/array of AudioClips, forget the enum for now imo
(add them in the inspector)
and yeah def add audiosource on it
I keep a few so i can split them inside the Audio Mixer so users can decrease different sounds like Bg musics vs SFX
It's a mockup for VR. But this specifically is just a static puppet that I drag by hand for debugging. Somehow it seems I forgot how the scale influences everything. Normalized vectors in combination with global wall position seem to give a stable reference after all. Now I need to define all the limitations for the green cube with this in mind, and then make it work from all sides... Thanks for your help!
At the end of the day you're going to need to specify some "collection" of potential sounds to play. Try adding a method like this to your SoundManager.
public void PlayRandomSound(params Sound[] options)
{
if (options.Length == 0)
return;
int randomIndex = Random.Range(0, options.Length);
Sound chosenSound = options[randomIndex];
//Play your shit.
}
```And then you can just specify the options by listing them off like this.
```cs
soundManager.PlayRandomSound(Sound.ZombieAttack, Sound.CoinTwinkle);
```Assuming an enum like this.
```cs
public enum Sound
{
ZombieAttack,
CoinTwinkle,
Eating,
Drinking
}
I agree with the others though that enums aren't the best for this.
how do I reset the deltaTime, can't find anything online?
wdym by reset the deltaTime?
you dont
I have a timer in a racing game and I need to do a restart button
make a timer
and I use deltaTime as timer
myTimer = 0;
and why would that have anything to do with deltaTime? you reset your timer variable
so reset the number you increased with deltaTime
ouh
I will work on converting from enums to a list of audioclips. Thanks guys.
bro i'm stupid
hey guys. can smb help me out? visual studio doesnt recognize unity code for some reason. although i have unity extension installed for the ide. and as always, theres no info on how to config it.can smb help me out? thx
!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
regenerate project files and restart visual studio after following the instructions
I have this error, and here is the script (line 27 triggers the error with mesh.enabled)
Can anyone help fixe it please ?
swap the two lines in Start
you're getting an exception on that first line because it hasn't been assigned so it never calls GetComponent
oh and always start debugging your issues with the first error in the console
weird that you serialized EmoteTrigger in inspector but not MeshRenderer :p
it worked thanks !
i have it
the mesh is the one of this.GameObject that's why xD
so what? assigning it inspector should not care where it is
then regenerate project files and restart visual studio
Hello, I have an issue, i forgot how you could teleport a player to specifc coordinates. Anyone can help pls?
!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.
!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.
double kill
does the player object have a CharacterController on it?
why do you have a direct serialized reference to the player?
You can just get the reference from OnTriggerEnter
Also
OnTriggerEnter takes a Collider parameter
not a Collision
they do have a Collider parameter, it's just named collision
I tried something
oh I'm blind
un try it. Your problem is the CharacterController
I forgot to change it yeah mb
Hey, guys! I have a small problem. I am instantiating game object but whenever I want to enable my options menu my clone game objects are still active. So, I have a game object to my prefabs and I am instantiating them. For one reason only my first original game object deactivates but my clones/instances are staying there. Can you please me?
but my timer is in a other script, how do I do that?
get a reference to the other script and call a function on it to do that
or use events
aReferenceToThatScript.myTimer = 0
ahhhhh
cuz ur probably only referencing the last one u create.. if ur using the same variable over and over
How are you activating them? Show code
deactivating the "original" object won't affect the clones
there is no link between the clones and the original
thx. it works now
I'm thinking of adding a UI Scale setting in my game and would do it like this:
Have a scene loader script that accesses all Canvas objects and sets their localScale to the setting value.
I was asking if there is a builtin Unity functionality for this or if this is how its done
Im creating some text ui in a flappy bird game for the score, and in the scene viww the text is easily 10-20 times the size of my flappy bird, but in game view it is so small that only a little bit of it fits on the screen. Another thing is that the positioning in scene view vs game view is not consistent
Where is the text on the canvas?
Can you send a screenshot of your canvas with the text on it
I tried to click on the canvas element but there is not overview or any indicators showing me where it is, but i see it in my hierarchy
sorry for the vagueness hard to explain. i have a script that simulates a guns recoil (on the camera) basically lerps the current position to the target position then resets to where it started. the issue is if you move the mouse down to control the recoil, after you stop firing, even if you are not moving the mouse anymore, it will reset lower than were it started. i want it to be in the same spot you started, or just not have it reset at all but every time i try and implement either of those the screen jus go crazy start shaking after firing a few rounds. https://hastebin.com/share/vikujugara.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
should probably put this in the advanced one
It's the giant white square in your scene
so, I'm modifying code someone else wrote, and I want to keep changes to a minimum. Is it possible to create a script that essentially "appends" to a class from another script, and allows me to add variables and methods to that class, and write code as if the appended methods were inside the class itself, private variables and all?
So, this New Text is pretty tiny in the bottom left corner of your canvas. That's why it's pretty tiny in the bottom left corner of your screen
Kind of. You can make extension methods:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
But you cant add variables or anything to that class
the text is humongious in the scene view and is so tiny in game though? did i do something wrong because those two sizes are not even kind of similar
Zoom out so you can see your entire canvas at once
yea just select the canvas and hit f then scale it how u want
You shouldn't rescale a canvas
i meant the text inide it
Right. That's what should be changed
the canvas itself is where it is for a reason, so it can use pixels as coordinates and have a 1:1 correlation between screen space position and transform
So you shouldn't touch that
how would someone make an UI that uses Int to categorize Objectives and have a script that gets rid of the tasks that are done and with that get rid of the interactive ui.
Is there a best method to define swappable behavior in the editor? The best thing I can think of is to have a class with an empty method that other behaviors (in this case interactions) override and hopefully that will let me swap them as a parameter in the editor?
like having an int system that categorizes all objective and when one obj is done it switches to the other obj "int = 1-10" " int = 1 = obj 1
You can use a dictionary and use the ints as IDs.
thx
You would use your int as a unique key and your objective as a value for the dictionary.
YT should have a lot of great tutorials aswell.
Hey! I am going to make a thread for that because I have no time for now so join that thread to discuss it tomorrow.
Yea that's a pretty standard way. There isnt really a way to store any script in 1 field without using abstract class or interface. And with interface you need to make your own custom editor functionality
How to disable already existed clones/instances of my game object?
Why does the enemy (red cube) ignore ALL colliders except the players? the orange cube also has a collider, i can collide with it, but the enemy completely ignores it?
How are you moving the enemy? Show the inspector of the enemy and orange cube
can someone help me to do a score board in my racing game? Idk how to sort them. I get values for min, sec, millisec and need to do a all time player highscore board and idk how to realise it. Google also doesn't help at all
transform.position = Vector2.MoveTowards(transform.position, playerPrefab.transform.position, moveSpeed * Time.deltaTime);
That's teleportation, that doesn't respect any sort of collider because you aren't moving it with physics
is MoveTowards not physicS?
Rigidbody is physics
No, it's pure math. The operative bit here is that you're just setting the transform's position to the new value
ohhhhhh
okay thank you i fixed it
wait why did i get 2 "start"?
Because you have two instances of this script
yea well, thats the hting, i dont think so
Instead of just logging the word "start", try logging gameObject.name
see what objects have the script
it just ignores the entire operation and prints out the little 'ö' despite my efforts to substitute it with some variable
no error tho
thx
For one, have you tried putting a log inside your if condition to make sure it actually reaches it?
Your string could be, for example, ö\n and you wouldn't enter this condition
one bomb only, yet still
Show the inspector for the bomb
There is a string.replace method
How can I create a method that only executes WHILE Im pressing a key with the Callback Context stuff?
checking if i gave the script twice?
cuz i checked that
This is the prefab, look at the one in the scene, after the second log appears
ah
ok yea it has the script twice, my thinkign process was almost right 💀
imma check my scripts see were this happens
https://hastebin.com/share/supiyubawo.csharp
For some reason, Unity keeps throwing this error that I appended to the bottom of this code.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It looks like the variable worldLocation of ReferenceTransform has not been assigned. You probably need to assign the worldLocation variable of the ReferenceTransform script in the inspector.
is assigning it in the class not good enough?
Where do you assign it
wait, maybe I am misunderstanding the meaning of the term "assign". Is that different from either setting a value to it or declaring it?
It is when you tell the code what Transform you want the variable worldLocation to hold
I dont want it to clone the current one i want it to use the prefab... how come it wont? i have dragged the prefab into that slot
script incase its needed: https://gdl.space/uwijixipad.cs
Instead of making bombPrefab public, make it a [SerializeField] private instead
its like its not refering to the prefab but the spawned bomb
You could very easily be changing it in another class this way
hmm i see, ill try
sounds like a tip to think about in general
Make it private and see if you get any new errors. That would be a different script modifying it which would mean that's your problem
This is the reason you generally should always use private unless you very specifically need to access it from another class
yea ill try it, but i dont think i do change it anywhere in any other script, sort of only one thing that uses that prefab
But that takes a single character, so I cannot squeeze in a whole new string, right? or am I missing something obvious?
my first time manipulating strings so I might be missing a lot
its still closing the gameobject
oh huh, so assigning "default" to worldLocation didn't give it a default valid Transform?
You just ignoring my suggestion or what
but ye i dont think u meant that as a solution just a tip i think
The default type for all reference types is null
ah. Is there shorthand for a Transform with zeroed out position and rotation, and a scale of 1 in all directions?
I tried a year or so ago, I'll try getting into unity again (I fell back into roblox development again)
(aka I'll be asking a lot of Q's later, may or may not have sent this message in the wrong chat)
Something is instantiating a clone, the script you've shared never changes bombPrefab, so I figured either something else was changing bombPrefab, something else is cloning the bomb, or you have an instance of Bomb other than the pictured one that references the instance in the scene
man none of this stuff works 😦
He's blocked me for calling him out on whining about Unity being "broken" when he messed up like a year ago, someone link him to this answer because I'm pretty sure it's the problem:
#💻┃code-beginner message
There is only one prefab and at the time i took that ss only one instance in the scene, the only other script the bomb has is this but ye it doersnt change anything but that instances renderer not anything in the prefab
ill check what spawns the bomb but i dont think there is naythign thee either
Can you show me a screenshot of the inspector for Bomb while the game is playing, before the (clone)(clone) is spawned?
this works, neat, thanks guys who pointed me in the right direction
Any suggestions on how to handle tutorial on new game vs no tutorial on load game?
I've searched online but no luck, keep showing me tutorials on a bunch of stuff but not how to implement gameplay tutorial within a game
its like inheriting the bomb prefab or something, or like copying the current bomb and using it as the prefab rather than the actual prefab
how could this happen
Ah. The prefab is referencing itself.
So when the prefab is spawned it updates the reference to "itself"
I'm not actually sure the best way to deal with this, hang on
In general, having a prefab spawn more of itself is a bad idea since that's a fast track to stack overflow-town
I think you'll need to have a different object pass the prefab reference to this object after you spawn the first one. The prefab is designed to replace references to parts of the prefab with their in-scene equivalents when instantiated. It's how you can drag in the Rigidbody of the prefab and the one in the scene properly references the Rigidbody on that object
How can I do "while pressing a Key" with CallbackContext stuff
action.started += ctx => /* Action was started */;
action.performed += ctx => /* Action was performed */;
action.canceled += ctx => /* Action was canceled */;
If the action is started, they you can consider that it's being held until it has been canceled.
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Actions.html
yikes
well uhm
what im trying to do is spawn 2 more bombs when the first one hits the grounbd, just that they have slightly different movement, so thats why i used the prefab itself to spawn those new ones
i suppose i could create another rpefab for the smaller bombs?
but that would be mean more scripts, and maybe even confusion down the line
or i could without a prefab somehow create the smaller bombs?
That would probably be the way to do it. You can even save it as a Prefab Variant, so changing the original one could affect the little ones
Guys do you recommend fishnet or Photon for multiplayer and which is easier and faster to implement?
I'mma be honest if you see fit to post in #💻┃code-beginner my recommendation is neither and don't make a multiplayer game yet
But if you really do feel confident in your abilities, #archived-networking would be where to ask about frameworks
i tried prefab variants once n it messed me up a lil, but thanks ill see what i can do
I would create a static database to store your prefabs instantiate as needed
Storing prefabs within prefabs can become confusing
Instantiate(Armory.bigBomb, transform.position, Quaternion.Identity);
Instantiate(Armory.bomb, transform.position, Quaternion.Identity);
Instantiate(Armory.smallBomb, transform.position, Quaternion.Identity);
u mean something like thsi but for prefabs?
so that way it doesnt inherit from itself
Pretty much, only thing is.. If the class is static then you cannot populate within the inspector.
can u elaborate on what u mean in "populate within the inspector."
You would have to create a method to call i.e. "Armory.LoadBombs();" that will load your bomb prefabs
At the beginning you will call this method to find and store all bombs for later use
The way i did that was put all prefabs I want to dynamically load in Resources folder and then have a code generator that looked for all resources with the .prefab ending, then create a class that looked like what you have above, then you could just load the desired prefab with Resources.Load(Names.xxx) while not even having to manually setup the names class
First time here, is this the place to look for answers to problems? Also I don't want to interrupt what's going on here if your problem solving things.
You are not interrupting, just ask your question, if it gets spammy we can resort to threads
Does somebody know how to Deactivate Inputs while "Blocking"??
lol, well im Day 3 of learning C# and Unity so im hoping someone can assist
Using the new input system, why is there started, canceled and performed, but not updated for hold actions?
I want to know the percentage the key is held before being performed?
Input System or legacy inputs?
if(blocking) -> dont read input
InputSystem
dont you have to add an if statement that tells the controller script to stop receiving inputs?
could be an updated method somewhere in the docs, but otherwise just make your own timer
this is the structure
i want that whenever OnBlock, It generates a shield which makes the player not to do any other input),
!code private void Awake()
{
if (instance == null)
{
instance = this;
}
iconHandler = FindObjectOfType<IconHandler>();
Baddie[] baddies = FindObjectsOfType<Baddie>();
for (int i = 0; i < baddies.Length; i++)
{
baddies.AddRange()baddies[i];
}
}
📃 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.
started: holding = true
canceled: holding = false
in update react to holding
Depends on how complex your stuff is, you can switch a different key map, you can create a seperate keymap that holds all stuff that should be disabled while blocking and just turn off that keymap while blocking
or just manually do ifs in the actions
Ok
Thanks
there's no real continuous callback with the new input system so you may need to poll stuff yourself despite it being more event based
the thing is that if I disable PlayerInput, the method doesn´t even execute
dont disable all playerinput, for example here i have 2 action maps, the UI action map is only active while a popup or menu is open: https://img.sidia.net/ZEyI5/CIfEyUmu61.png/raw
Just move all "ignored" actions to one input map and disable that one while you are blocking
sorry made a correction to that code i posted, this is my issue.
you can disable the input, but honestly I'd just read the state that you're in and just decide not to move
or w/e behaviour you're looking for
Array doesn't have a method of Add like the list
I am basically following a tutorial and everything looks correct to the letter but his works and mine doesnt
actually you're adding it to itself eh
ill give a full picture to show more
Is there a this that you're missing maybe?
looks like you're missing a this
Sorry, I dont get it
its in this script
isnt there another way to do it?
basically in the class scope you have a baddies in the class outter scope, but in the inner scope you also have a baddies
so you need to clarify what baddies you are using and to do this you use the this syntax keyword to clarify that this is the class scope variable
ok, i see the issue. This is day 3 for me so i understand alot of what i read but dont know how to do it on my own
or, just dont use the same name in the inner scope
ye np
hey Mao
Ive realized if I use Unity Events for Inputs it doesnt matter if I disable a Script
first
is that true?
and also, how can I solve thos?
disabling an object usually just stops any update loops, but methods are still callable
so if you want to prevent using that object's methods completely, then consider using your own flag
so this is jus ta way to make more effecient? definitely something ill keep in mind for future projects but for my current simple project and for my peace of mind (cuz this sounds like a lot of new stuff, doesnt sound easy to set up especially as im solo devving rn) i think it would be a safer choice to do it manually
although.... it is also a learning opportunity... hmm
and sticking them into each method call
public void NewMethod()
{
if(!activeBool) return;
}```
I mean its not really unsafe to generate it, its a simple code generator, im currently looking if i still have the code somewhere
how in depth should i go into linear algebra
okay so I should include a bool in all of the methods?
which controlls if I can call them?
unless you want a headache, learn what you need in that area 😄 instead of pre-learning
linear algebra is a very useful field tbh
oh sorry you mean the input event binding not unity events. You can just unsubscribe, or disable the input directly.
i've mastered solving systems of equations with matrices lol which i figure is just the bare basics
but you only need a very strong understanding of the basics of vectors, dot products, and geometry for unity
I have thsi script
but whenever I disable any Script if I press a key related to the method it still occurs
and if i want to be proficient in different engines i should go as in depth as possible? or is just baseline across everything
tells you how to enable and disable actions
linear algebra is used in a lot of high level science
I am using Ujnity Events
so to learn the other parts of what i'm trying to learn, i should learn all of this? 🥲
i'm following a youtube series and taking a lot of notes
quantum mechanics, ODEs, PDEs, anything with waves needs it, computational stability needs it, any multivariable math needs it, high level statistics
it’s basically mandatory for any of those
Ah, ok. I don't usually use unity's events but I would assume you can unsubscribe similarly to c# events, but otherwise the flagging method I've shown is straight forward.
if you don’t know linear algebra, you can expect to struggle in higher level sciences
otherwise read those documentations I've linked and bind input to the class
Okay, thanks
https://roadmap.sh/game-developer this is what i've been using as my learning plan
if you want to be a great programmer, it is also naturally required, as there are several things that require an underatanding of it
you don’t need a full course on linear algebra to do game development
How can I unsuscribe
yea man but idk man i mess up simple things so idk 😅
in game development, if you don’t understand vectors, you are shit out of luck, friend
like, really screwed. lots of things you just can’t do
is it possible to create what looks like a Transform, but isn't tied to a game object?
What does a Transform look like in your opinion?
But yeah, you could create a struct with some values similar to a Transform
The answer to is it possible: yes. Is it worth creating? probably not.
What are you trying to do exactly that's stopping you from using a gameobject
Unity works in gameobjects, so you would want to make a gameobject with a sprite or something for a transform, and put it in the desired spot
I suppose nothing, except maybe my current workflow? Basically I want to make a reference point on an object, but for now I did just make it as its own object with its own script.
it is worth creating
Why not just a Vector3 variable?
with its own rotation
but you do need to make a gameobject for it
Then a struct holding those values
If you need more than that, just use an empty gameobject
yep, gameobject with a script that tells it what it should be, and some sort of rendered thing to be controlled.
right now I'm just rendering a gizmo (though accidentally discovered in the process that if you draw a gizmo using several colours, then the lines drawn later will always appear in "front" of earlier lines)
This is starting to seem super inefficient
Compared to the extremely cheap empty gameobject
I mean, the gizmo is literally just to see where the otherwise empty object is when its parent is selected
gizmo is unique to editor mode
it will not display ingame
gizmos are literally designed for this sort of thing in editor mode.
I was just thinking you seem to keep recreating bits and pieces of a gameobject. Just not sure why you think this is worth it
I meant inefficient in terms of effort
i do the exact same thing in my game for anchor points
my objects have a specific point considered to be its grid origin position, which i display with gizmos.
player has no business caring about this
I like being able to see the area my code will affect. This gizmo, assuming I didn't screw something up, shows the exact area that will be affected by my Physics.CheckBox/Physics.OverlapBox call.
Okaaay, now we're getting somewhere. That is a good use for what you're doing. It was just so vague earlier
I was thinking it was an xy problem
that is a good use for a gizmo
how can I require a button to need multiple presses before becoming inactive?
I currently having a button working that will SetActive(false) after being clicked, but I want to require an amount.
Something like create a variable buttonPresses and then assign it a static amount?
disable the button component using a function
OnClick, increment a counter you make
No need for static (if you mean the static keyword)
ahh, so similar to setting something active if you need x currency to buy?
but in reverse
yes
though, the one I made for the reference point is this one, which is just there to remind me where the empty game object is when said object isn't selected. Maybe it was a bit of a waste of effort, maybe I'm just procrastinating a bit before getting to my next task >.>
i made a static class to make stock shapes with gizmos
like DrawArrow, DrawTriangle, DrawX, DrawRectangle…
do you know of any way to change the order in which lines are drawn, based on where your viewpoint is?
i honestly have no idea whats wrong here the error code is Assets\scripts\Launcher.cs(18,5): error CS0246: The type or namespace name 'Players' could not be found (are you missing a using directive or an assembly reference?)
Do you have a script called Players?
Perhaps it is actually called Player? (With no S)
i mean im following this tutorial
and ive done it exactly as he has
there is no player script btw
I've heard close to 200 people say that now, and only 2 or 3 were correct
They could not have had this code if there is no script called Players
unless im too tired ive triple checked it so many times
Show a screenshot of their code
Player, not Players
As I said at first
There HAS to be a Player script for this to work too. They don't have an error, so they made one somewhere
could Player be defined in either Photon.Pun or Photon.Realtime? Would that work instead of making a Player script?
Could have sworn they call it something else, but perhaps.
Still need to make it singular instead of plural though
If it is part of Photon, quick fixes may find the using for them
So, worth a shot
can someone help me with c# i have been making a parkour game for my first projects and so far i have just been copying scripts and combining them can someone help me
What specifically do you need help with?
Show the code and any errors
do you have any background in any programming languages?
i know some html and python also just a bit of js
https://www.w3schools.com/cs/index.php
This is good for learning c#
There are also resources pinned here in this channel
ok thank you
And of course !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Quick Question what would be the easiest method of storing some very bare savegame data? All I need to save is a single integer for a highscore
PlayerPrefs probably
unity learn all the way 
and the book unity in action
i've been reading that one a bit
I want to know if this Enemy system is fine?
I have an Enemy.cs class [https://hastebin.skyra.pw/egimuyacuk.csharp]
and an Enemy, called the Acidic Slime [https://hastebin.skyra.pw/topeleriku.csharp]
for future enemies, I will just also derive from Enemy.cs;
Is this code fine? the derivation and all? or is there a more efficient way
That's a very broad question. We'd need to know your intentions, how do you plan to expand the game, etc.
And also depends on the style?
The better way would simply be two components
I myself prefer making things more modular
An Enemy component - has the basic HP, take Damage, give XP etc
and a SlimeAI component - controls the special movement and attacking for slimes
there's not really a good reason to use inheritance here.
i see
That requires you to reimplement the health etc on every script
i don't see what it gains you over just having a separate component
I think the Enemy dying should be an event that the XPManager can subscribe to
SOs
what does "subscribe to" mean? any example
thanks
Unity may handle events differently, but start with the source
but i hate how the .NET guide encourages the EventHandler pattern
it's fine for .NET apps
not the best for Unity games
I mean, yeah, but I guess starting with the OG guide ain't that bad
yeah it's fine
I have this problem with Unity devs making everything observe patterns
This is a good one
https://www.youtube.com/watch?v=WLDgtRNK2VE
In this second devlog, we look at how we employed ScriptableObjects to create a flexible and powerful game architecture for "Chop Chop", the first Unity Open Project.
🔗 Get the demo used in this video on the Github branch:
https://github.com/UnityTechnologies/open-project-1/tree/devlogs/2-scriptable-objects
(compatible with Unity 2020.2b and la...
C# events are basically already the observer pattern
I think he's talking about people following patterns as programmers
Yes, but Unity usually encourages making it again.
I mean, not Unity
ofc
For example, the observe pattern with SOs. Do you really need it?
"It's better for designers" is it really
Instead of just making an event, you'd create an scriptable object for the event, and a game object for every listener, etc.
I think it overcomplicates something that is already well made by the language
would just like to say I did it, so thank you again! I appreciate it so much actually lol
Anyways, going out of scope here. I think that's a too deep of a topic to talk on the #💻┃code-beginner lol.
So for that, sorry.
That's an acceptable topic for a beginner . . .
Oh, I mean because it isn't about scripting really anymore?
So i think it would go out of topic
You can talk about coding concepts. That's a big part of programming, and most beginners are just getting into design patterns . . .
True
Well, my main criticism is how there is this pushing for the "remaking" of the observe pattern using scriptable objects when C# already does it well, so it only overcomplicate things.
Suddenly there is so many layers you can't even know what is using what and what is calling what
It is because designers can create their own events, set listeners (to these events) on GameObjects, and invoke the events from the inspector. This frees up the programmer and needing to wait for updates
It's one option for a person/team to use . . .
yes, not having too many dependencies and links are good, but cutting them out completelly makes the code so hard to fix when something is wrong
I wouldn't call it a push, but a designer-friendly method . . .
It's just an option for non-coders . . .
There are definitely issues with it—the layering you mentioned . . .
It's similar to using C# events vs Unity events (which I've taken a liking to) . . .
I mean, I'm totally not against it
In fact, I do use it
But a lot of things that could easily be solved with a line of code gets pushed into a code/design pattern
hey how would I convert a mouse.delta to a vector2? I looked through documentation and I could get the individual fields, but they returned an axiscontrol type instead of a double or float
Can't you do ReadValue<Vector2>?
Try .ReadValue()
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.Controls.Vector2Control.html
yeah that's what seems to be here.
I guess I should have read a little better, my bad
thanks
alright so I clearly have no Idea how quaternions work yet so heres some naive code of mine:
cameraTransform.position = playerTransform.localPosition + offsetLoc;
mouseRot = Quaternion.Euler(mouse.delta.ReadValue());
playerTransform.rotation *= mouseRot;
cameraTransform.rotation = playerTransform.localRotation * offsetRot;
My idea was if the mousedelta returns an x and y value, and the z value is zero for the euler, then it gets convertet into a quaternion for rotation, then in order to apply that rotation, I use multiplication, and since it only has x and y euler values it only rotates in he x and y local space
right?
is this like topdown 2d rotation
no, third person
the mouse rotates the character and tha camera strafes behind
think I used localrotation wrong
there's a third person template from unity that you could probably rip apart
it's in the hub if you're interested
yeah, I just want to get in the habit of learning how it works. I think the axes are misaligned, because up and down are rotating clock and counter, like the up and down of my right side
left and right are doing up and down
I usually just use angleaxis for stuff and rotate on the world axis by an angle in xyz ordering
I am having a really weird issue, I have an image used for transitions, that in a few not all but a few scenes wont show up in, any ideas?
And you believe this is code related?
Can you show the code that would have to do with this?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so uhhh, im trying to make a sonic like game.
and i got movement working-ish.
i did use chatgpt to generate the code because i have no clue what im doing and i wanted to save some time
case in point, breaking and jumping doesnt work.
here is a video of very much what i mean.
and the code.
Use !code to post and send 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.
the idea of the game is to feel like an early 3D pc game, think of it as sonic Jam's hub world or sonic R
aight
Also, if you have no clue what you are doing, how can we provide help that you will understand or use to fix your problem?
Use the links provided from their message to send your code . . .
true, might of worded things improperly.
i do know what is broken, i do know what i want to do with the code.
what i dont know is HOW to do it properly/fix it and i have some slight idea of how to fix it but i dont really know how to. idk if i made it clearer
That is what I was thinking, it is the same code as some of my other scenes but this ones it doesnt show...
I think it is a scene setup issue.
Show the scene hierarchies in #💻┃unity-talk
been a bit since i've last used Unity soo yeah
Okay thank you
so i know i can't use a variable from one void to another (e.g. define in start void, but use in update void), but i dont want the variable redefined every frame. what should i do? fore more context, the variable is just textmeshpro.GetComponent<TMP_Text>()
They're called methods, not voids
Make a field
Also that thing you wrote is not a variable it's an expression
oh sorry, thanks
when I import photon pun I keep getting
InvalidCastException: Specified cast is not valid.
It's an error that goes to PhotonNetwork.cs
photonServerSettings = (ServerSettings)ScriptableObject.CreateInstance("ServerSettings");
I've search everywhere and nothing matches this
Why use PUN? It's incredibly dated
Even that code snippet is dated
Why isn't it using the generic form?
well it's cheap and simple but also I'm not doing it for me
what does this mean?
wow I changed it and it works tysm
I'm developing my first project in unity and I'm stuck at how to detect collision with a TextMeshPro object.
Would someone be able to help out with this, please?
you need a collider
Collision detection is a physics thing.
You use Colliders and Rigidbodies for it
TextMeshPro has nothing to do with physics
Should've added more context. I tried adding a BoxCollider 2D to it.
The work around I've been trying out is making the text a child of a 2D square, sizing the collider to match the text, adding the BoxCollider 2D to the 2D square parent, and enabling the isTrigger flag.
First question
When you say "TextMeshPro" are you talking about the UI version or the world space version?
If you're talking about UI then this is all completely off base
UI lives in a completely different coordinate system than physics objects
The UI version. I tried changing the layer to default. I understand what you are saying about the use-case of having a UI Text object though, that it's not intended to be a physics body.
I guess that why I'm here, to figure out a way to get the desired outcome :)
All I care about is having a visual of a text, and detecting when the player collides with it. Is there a way to achieve this?
Use the world space version
That's the simplest way
A more complicated way is write some code to position a world space invisible collider in the position , size and shape that corresponds to the UI element converted to world space
Got it, I can totally use the world space version. To clarify, this would be just changing the render mode to World Space?
there is mesh version of TMP too
Yeah, I was looking into it - added a rect transform, added the collider and resized it, but I couldn't get it to work. Is that what you have in mind?
you added it from here yes?
Oh, no, I just used the one under UI. I'll try the one under 3D obj
No
Not the UI thing at all
Yes this
And don't put it inside a canvas
Okay, thanks!
public void OnDrag(PointerEventData eventData)
{
mousePosition = eventData.position;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentTransform, mousePosition, Camera.main, out Vector2 localPoint);
mousePixelPosition = localPoint;
VOnDrag(eventData);
}
This script isn't corrrectly converting the mouse position being provided into the local space equivalent for a given canvas element. Can anyone help me figure out how to use this function correctly?
it IS getting the correct mouse position, but when I use it in the ScreenToLocalPointInRectangle, it's returning a far lower value, and I'm not sure why
Okay, I haave no clue what I did, but apparently it is now registering correctly...
I think it had to do with what anchor orientation the object had?
you added it from here yes?
IEnumerator CheckHoldAcceleration()
{
if(accelerationCheck){
holdTime += Time.deltaTime;
if (holdTime > 4f)
{
accelerationTimeThreshold = true;
accelerationCheck = false;
}
}
if(accelerationTimeThreshold){
accelerationTimeThreshold = false;
instructionText.text = " ";
currentText = "The car is now moving!";
instructionText.text = currentText;
yield return new WaitForSeconds(5f);
currentText = "Good job! \n Now Press SPACE to brake!";
instructionText.text = currentText;
if(Input.GetButton("Brakes"))
{
Debug.Log(Input.GetButton("Brakes"));
brakeCheck = 1;
//Debug.Log(brakeCheck);
}
if(brakeCheck==1){
currentText = "Well done!";
instructionText.text = currentText;
checkFirstTask = 1;
}
}
Here i want the message in my canvas object to change to "Well done!" When i press spacebar, which is what ive assigned Brakes button to, but nothing happens when i press the spacebar
diffcult hitting GetKey by the time this runs
You could use something like WaitUntil
Yea last time i asked something u said the same thing, so i should just use waituntil instead of if condition to avoid the frame perfect input right
did you try waituntil then ?
...
yield return new WaitUntil(()=> Input.GetButton("theButton"));
...
Waituntil, yes this is what i need, i knew something like this would be there, thanks, will try
Its tough to findwhat i need in unity docs
Especially when i dunno what im looking for
true sometimes you need to dig in docs
I keep getting the error
Assets\SaccFlightAndVehicles\Scripts\Other\SaccTeleportButton.cs(16,17): error CS0246: The type or namespace name 'BoxRegion' could not be found (are you missing a using directive or an assembly reference?)
yet I have this script:
https://hastebin.com/share/osenonowig.csharp
Anyone know what's holding me back? I can post the SaccTeleportButton script as well if needed, though I'm still trying to troubleshoot a number of things on it.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how do I define a type?
With the class , struct, interface, delegate or enum keyword
(depending on what kind of type you wish to define)
I have a gameObject with this script on it:
https://hastebin.com/share/osenonowig.csharp
How do I declare a variable in a different script that uses this as a variable type?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
BoxRegion myBoxRegion;
Variables are:
type name
My guess is that one of your scripts is inside an assembly definition
And it's trying to reference another that is NOT
how would I check that?
one is in Assets, and the other is in Assets\SaccFlightAndVehicles\Scripts\Other
Sure and that seems like an asset
Most assets have assembly definitions
Is there a good reason you're modifying code inside an asset?
That's generally poor form, especially if you don't understand assemblies
The quick fix here is putting both scripts in the same folder.
The better fix is there's most likely a better way to achieve what you want than modifying code inside an asset you downloaded
that's just where those two different scripts were made. I put BoxRegion in the Assets folder because I wanted it to be more generic, and possibly reuse it in the future, while SaccTeleportButton is specific to a specific asset.
both scripts were made from scratch
You don't want to put the teleport button script inside the asset
That's what's breaking everything
It's also really weird to put your code in the namespace of the asset
Put both scripts in Assets and not inside the SaccFlightAndVehicles folder
And I highly recommend not in their namespace but namespaces aren't actually relevant to your issue here
that's where the original creator has all the other scripts
moving both my scripts up to Assets breaks more things when they get referenced by the script I modified. Moving them down to Assets\SaccFlight\Scripts though fixes the issue.
Right, further illustrating why it's a bad idea to modify the asset in the first place
You are now spiraling down a dark path where all your scripts will slowly need to live inside that asset 🥴
though, what's the worst that could happen? And to be fair, pretty much everything is living inside those assets
The worst that could happen is you frequently have issues like this
Well, no, that is likely not the worst. Just the norm
Maybe the asset updates and you need something from the update. Then all your modifications are gone and all your other scripts are trapped and broken
Ooh yeah, migration will be a pain. Though, is there a way to make a script that essentially just adds functions and variables to an existing script, and is able to use that script's private variables and functions?
What's going on?
Not generally, but that's very rarely needed.
The bigger thing is it's even rarer that a modification you make inside an asset should need to reference anything outside the asset
You would simply add more open access to the thing and then do the interaction from outside
What exactly are you trying to do
I mean, it's not one asset I'm modifying. Just about everything relevant to the scene is in Assets\SaccFlightAndVehicles\
I'm adding components to prefabs, so that I can use them for a game world in VRChat
Can't you just make a prefab variant and add your components to that?
Or just duplicate the prefab
Both of which can be done outside the asset
They are said to have a good modding community, which you should definitely ask questions to instead
I do ask them questions, but usually when it's specific to VRChat
It's still best to just ask them, as described here <#1201856945791705108 message>
Having any limited access, or just scripts in general that do things you may be unaware of will be a massive pain to debug in here, while it would be common knowledge in the correct chats
one big difference though is that this is specifically a channel for beginner coders, and in the short time I've been here I've gotten absolutely fantastic knowledge that's general to Unity. It was just this particular case in which I couldn't understand why one script couldn't see another that was tripping me up.
hi! is there any way of making power ups that are permanet through out the run but not for each time you do a run?
example: you have a primary fire and you want to make it be double shoot when they get that powerup, but the next run they will have the normal shooting version
I am currently doing a game where I will have to implement that. It depends of everything else do you want to implement
Like if you don't want to have like any peogession between runs you can just reload the initial scene, without saving anything
yeah but how can i even implement it
You probably want to have a main menu
Just load the menu as any other scene and don't do anything to save anything from the run itself
should just have a big-o method that resets the states of everything
or reloading the scene works too
im talking more of the powers itself
making them seems a bit weird how i plan to do it
if i want to modify 3 times for example the bullet it will be a bit spaguetti coder
youtube usually have basic bits of code to follow for stuff like that
I mean, the optimal way should be to have like two different datas stored, the overall game data and the run's data in case you want to have progression between runs and be able to quit a run an come back late, but honestly that's kinda a lot of work that you don't really need if you are doing something small and contained
im doing something basic just to learn how things work
I am doing it by just adding bools to the stuff that can be modified. Like, is this modified active? Yes? Then do X
btw srry if im slow at answering i wanted to take a break and im in a game now xD
a game of what
but if you have multiple things affecting the same stat would it bug out?
LEAGUE OF LEGENDS?
Makes the modified stuff kinda code bloaty, but it is readeable and organized so....
sadly league
Playing Aurelion? YOU HEATHEN.
thats what i meant
i had in mind smth like that
but i thought there was a more easy way
more than easy i mean clean
For example, I got a proyectile for the player and it has all these stats where it gets damage, range, speed, size, knockback and all that straigh up from the players stats, you can do exactly the same for powerups. Does the proyectile bounce? How many times? And just add it one by one
As I said, seems, really, really bloated once you start adding more stuff, but should be fine
yeah thats what my idea was but as you said it seemed to bloated
and thought that maybe there was some unity implemented function that helped or whatever
No because that does not make sense
You can have static methods in interfaces but this is not supported in Unity as far as I am aware
Nope, it's a c#11 thing and Unity is still on 8
Someone give me a coding tip. Need to add one to my collection.
dont use chat gpt
I have had mixed results with that thing.
It's sometimes good with algorithm requests, or at least "stimulating your brain" with some potential implementation.
But it really fucks up sometimes.
Using struct is more likely going to make your code worse than improve it
Why is that?
Because people think struct is a better class without realizing just how much they need to do to actually make structs work properly
The tip is more like... use chatGTP, but never trust it
Meh, slap the in keyword on some method parameters and it'll be fine.
I really only use structs for stuff I know will be short lived.
Events usually.
It's fine to use but don't blatantly copy paste code over, especially as a beginner
It's a very good helping hand
Ask for a potential implementation and it would probably give you something to start working with. Or ask for something superspecific if you want to copy it. Or you can just try to copy a full chunk of code and see how it runs, but never trust it would do it properly
I have another one. Consider supporting this in your project: https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2022
And also having a Directory.Build.props file in your project with this:
<Project>
<PropertyGroup>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>All</AnalysisMode>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
</Project>
Combining these two is a very good way to write better code, assuming you configured it properly.
wtf is this
This puts in very strict code analysis, combined with various rules that are considered best practice
Takes a while to get used to but almost all rules are something you should learn if you want to improve as a programmer
I'll give a tip.
Guard clauses are cool.
Use them.
Deeply nested functions are ugly for my monkey brain.
else is the devil
Not really, but guard clauses are generally a good way to define a proper flow in methods
But let's not bloat this chat with any more off-topic, because this is not the point of it
mmm fine
Is there a way in the script to differentiate between which trigger is touched first?
You probably want to be nested differently with empty parents and different names, cause that seems really confusing
What are you even trying to do here? Like check for a combiantion of ordered triggers?
So the purpose of this is to check where the player is going in the map and spawn the next section appropriately.
The first trigger "behind level trigger" is supposed to change the section behind the player to a level shower in case they go back there.
The 2 forward triggers are for checking which direction the player goes (wrong or correct way) and then spawning the next section.
the 2 backward triggers are for checking if the player after choosing that direction then decides to go back (if they try and cheat the game), which they would then be responsible for spawning the level 0 sign.
I'm still quite new to unity, so I haven't been able to think of a better way of doing all this 😅 but could you elaborate on this :)
So... you want to have múltiple colliders cause you want to know in which direction the player is moving?
Is that really even needed though?
Well it's more important for knowing when the player is moving a to a certain place
So I can spawn the next section of the map
To explain it more simple, I'm trying to create a simple version of the game "Exit 8" if you've heard of it
Pretty sure you just need to know WHERE the player is and not in which direction they are moving
But yeah, you could just dissable and enable colliders as the player passes through them
Like if the player is entering this direction check if they also pass through the next
Yeah I had written some code for that, but I realized I wasn't able to check for which trigger they pass through
How are you differenciating between colliders?
Yeah that's the problem I ran into
As I asked
As I said, you should have each collider assigned to an empty parent so can easily ser which one you are checking
An empty parent? Or child?
daleo idk if you remember me im the power up guy, could i take a look at how you did it?kinda curious and im having a meal so i cant focus on programing
Like this you mean?
Mostly. Isn't that making it easier for you?
Well I'm unsure how I'd then use these in the script?
Should I place the script on each of them and then just check for what the name of the object is?
Or is there a better way
Just drag the entire parent in the collider slot
But how does that allow me to check which trigger is activated?
yes, you can have a script + collider on each child object and then have those directly call some function on the parent
You can now tell which collider is which and which one you are checking
How.
Before they were indistinguishable
Cause they have the name of the parent
Dude, I'm asking how in the script I can check which is triggered.
You cannot give the component itself a name
That's been my question since I posted.
call a function on the parent object from the script on the child object
Ok, and how do I do that.
As I've said before, I'm new to Unity, so I'm not sure how to use all those, could you give a small example?
Unity events are just a tiny bit more complex. Just place the collision check on a new script on each of the collider objects, and have a reference to the main script in them so you can call whatever method you want to call from It when the players collide with them
and have a reference to the main script in them
Yeah I'm unsure how to do this
the triggers shouldn't be on the same GameObject. Instead make a new gameObject for each trigger.
So you want 5 scripts basically?
And each having an instance of the main script
many ways, https://unity.huh.how/references you'll want a serialized reference, something to drag in inspector. With UnityEvent you can directly call a function on the parent object if you wish as well and its all setup in inspector for you. you just need to invoke the event from the trigger code on the child script
Well, it depends of how specific you want to be. What you want to do seems pretty specific, so you need specific scripts instead of something more generalist
So as said earlier, I want to be able to spawn and despawn the sections and level signs
Would that need 5 scripts?
Sure, but under which conditions?
These
If you want to check for an specific order of collisions, you could have a script that handles collision detection on the colliders and just send a boolean to the second script that does the logic. Like "is this triggered correctly?"
But each of the colliders would need to have a copy of the first script
Yeah, so I'm thinking, wouldn't it be easier to make a script that checks the name of the object it's on
I have another script that handles map spawning
So trigger manager takes care of... managing which trigger is touched and then it has an instance of the map spawning script to then call whatever method I need
this is all possible under 1 script, have you tried using unity events yet? even if not connecting it to any parent script, try to just see what they do and mess around with it
You could swap it around and place the collision detection on the player and check for the name of the collider the player is entering, yes
You can do that
Is ir better for you though?
I've nevet touched them, could you give a short example 😅
its just a matter of adding a UnityEvent field to your trigger script. the docs have an example although not the best imo.
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html
But really you just need a public UnityEvent eventName;
So in all, I would still use 5 children to the main thing with each having a trigger on
So is there any difference between that and this
Other than using an event to call the method
just to preface: string (name) based anything is bad. its fragile, you change the name accidentally and suddenly you have a major bug.
also check the name of what object? the issue was that you had no way to differentiate between triggers. It was suggested above that the child object call a function on the parent object. if you are trying to find an alternative to this, how are you gonna know what name of the object was hit if you dont call any function? if you intend to pass the name through a function, then just instead call the exact function that you want to execute
I get it's fragile, but I'm not looking to make this the best game ever, it's just a quick side project for fun
And it seems to work
that is terrible way of doing it
If it's a quick side project for fun, then why not learn and do it properly? You will very quickly learn to hate this. Wait until the day that you accidentally change the name of one of these objects and dont notice. Itll go from "everything works" to "why wont it work??? I changed nothing!!".
At least with unity events or anything else serialized in inspector, when you notice it doesnt work, you look at the trigger object and see "oh its missing".
change it to a switch statement switch (score) { case 0: Debug.Log("Score is 0"); break; case 1: Debug.Log("Score is 1"); break; case 5: Debug.Log("Score is 5"); break; default: Debug.Log("Score is not 0, 1, or 5"); break; }
Do not do that
I read the docs you sent for events
Idk if they're outdated, but I'm not getting the AddListener method on mine
Nvm sorry, IDE error
Could you just help me understand what you mean by wanting to use UnityEvents?
Like how would you want me to use them.
Unity events is just one way to simply do it. First start simpler because I think this is not even the first step. You need a script which has the functionality that you described above about spawning certain things. Make these things and put it inside a method.
Next you can actually worry about calling these methods. UnityEvent is just one way to do it from another script. Like for example you would now have a script with OnTriggerEnter, and inside that you invoke the unity event. In the inspector, you would setup the unity event to call a public function (the functionality you made in the previous step) which would be on another script, likely on the parent object here
But also there really should be a lot of tutorials out there for unity events
using System.Collections;
using UnityEngine;
public class Movement : MonoBehaviour
{
void Start()
{
StartCoroutine(MoveObject(transform, Vector3.right, 15f, 3f));
}
IEnumerator MoveObject(Transform obj, Vector3 direction, float speed, float duration)
{
while (true)
{
float startTime = Time.time;
float endTime = startTime + duration;
while (Time.time < endTime)
{
obj.Translate(direction * speed * Time.deltaTime);
}
yield return new WaitForSeconds(1f);
}
}
}
why the editor is crashing bcs of this code of piece? Isn't logic is right?
all I wanted move the cube every 1f seconds towards to Vector3.right side
The inner while loop looks dangerous
Because you have a while loop that will never exit because the values are never updated and you never yield inside of it
its works when i did that. But the movement doesnt feels right when its moving. As you can imagine it'll update the position every 1f
its strange.. but what if i would give the values before run the Coroutines. Do you guys think it would work?
Whatever the case, you've got an infinite loop
yes yes i realise that ill try to look for another solution somehow then
The time at the beginning of the current frame in seconds
https://docs.unity3d.com/ScriptReference/Time-time.html
Meaning the time since the beginning of this frame will never be greater than some time after the beginning of this frame.
If the yield instruction used inside the inner while loop was null, it'd move every frame.
Yielding for a second only after the duration has been met.
ah yes, im sory. didnt realise that. somehow I'm thinking i have to put some value inside of yield
Is there a way I can delete everything from a unity file project and start from zero ?
Create a new project
Been working on a player movement controller which is a modified version of the provided third person controller template, but it's behaving strangely. Basically, sometimes it just moves perfectly fine, but other times it sticks to where it is and won't move at all, with a max speed of like 0.02, before just randomly moving at the speed I define. Got the code here -https://hastebin.com/share/eboyusanep.csharp - and a video showcasing what is happening. Why might this be behaving this way?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There's a property on the CharacterController whose name I don't remember right now
Something like "minimum movement distance"
Reduce that by a factor of 10 and see if it behaves better.
that's what it's set to at the moment
that helped somewhat, but even with a value of 0.0001 it gets stuck for half a second
and what if it it's a flat zero?
If you accelerate slowly, then it's possible that you move less than the minimum move distance on the first frame. And since you read the velocity back at the start of the next frame, you can wind up sitting there until you framerate randomly drops and you accelerate enough to get past the threshold in one frame
makes sense
flat zero has it working flawlessly
so I take it, either raise the speed or set that threshold to nothing
what are the downsides to setting it to zero?
if any
I'm not really sure. I guess it can help filter out unwanted small movements?
how does someone make an UI system that changes text based on events, so when I ineract with a obj it triggers an event and that event triggers a change in the UI
I use root motion for all movement in my game, so I don't actually accelerate the character. I just move the blend parameter around.
I assume it would cut out any jitters, yeah
I'll keep it on zero then until I come across an issue
so in my case, this problem didn't come up
fair enough
Hey guys, as you can see in the video, my problem is that player if he touches the wall he will just keep sliding on it and I cant walk anymore no matter what I press. My Player is Rigidbody based its not Character Controller. How can I fix this issue?
help, this thing is not working, unity say "Assets\Objsystem\Scripts\Objective system\Objective.cs(31,9): error CS0103: The name 'thisText' does not exist in the current context"
and I have no clue how to fix it
I followed a video and did exactly like he did but nothing
Please configure your !ide first
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
Your issue is a lot easier to fix after you've done this too
hi ! is there a way to report a BSOD bug on this server?
The default value is 3 or 4 zeros before the 1
Your editor is not configured so please follow the steps for configuring Visual Studio by clicking the url in the bot's message
You are expected to have it configured if you want to be helped
The variable name declared is theText not thisText
should I change the one who has "thisText" or just the ones that has thetext
Did you mean this.theText or just change it to theText
No clue I followed a yt tutorial
oh so I can just change the thisText part
to theText
Yes that should fix it
Assets\Objsystem\Scripts\Objective system\Objective.cs(31,17): error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context
I got this instead
Configure your !ide first instead of fixing the issue
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
@violet token Please do not help people with a misconfigured editor, have them configure it first
I tried but I have no clue how toooooooooo
it is in my assetstore
Then say that instead of ignoring this, this server requires you to configure the editor first
What do you mean no clue? Just press the bot's link depending ont he editor you use. Did you install Visual Studio manually or did you download it when you were downloading Unity?
manually probbably
Then follow the steps as pointed out by that page
ok now I've downloaded the things and shose n that
still have no clue what to do
compare that error line 31 to line 29 and find the difference between the two . . .
check letter by letter, one by one . . .
Is it good idea to make character controller with kinematic rigidbody?
It tried, but it really hard and i didnt even found any tutorials for it..
why not just say
public Text theText ```
no clue man, Watched a yt video and yuh
See how clear the error is now? Just find the red underline
if u change the public GameObject theText to public Text theText and assign it to your gameobject, its gonna take your text component anyway
think of () as the invocation. it is needed to actually call or invoke the method. it's much easier to see the problem when your IDE is confgured, no?
yeah code does look a little better to
Good job on configuring it 👍
haha, that's the next step, right?
imma see if it works
and then theText.text = "anything"
yeah no errors
imma make the thingy more worky
IT WORKS
now the question begs
can I connect that code with interaction with object
Hey all, kind of struggling how best to go about writing this.
I have a base class we’ll call “Enemy” and other classes for specific enemy types inherit from Enemy, and define their own custom stats, death behaviour, etc. The issue I’m running into is how best to actually instantiate them, afaik I can’t just pass the class type as an option into some function for it, and I’m also unsure how best to give each class prefabs, as it’s something I have to define inside of the editor and I would have to attach the script to a game object
If anyone has any suggestions that would be appreciated
you would instantiate the enemies by using their prefabs. each enemy type would have it's own GameObject with the correct script attached to it. save that as a prefab in your project folder as a template for that enemy type . . .
That makes sense, thank you
just remember to set the default stats for each enemy type on the prefab . . .
is it possible to have an interaction activate the UI
that is done with the script that I was wobling about
Everything is possible with the right code and setup.
word
's that are not helping me rn
haha
Does anyone have experience implementing steering in a car without wheel colliders.
activate a game object with a Canvas on it
how
yeah thx
im still kinda clueless cuz I got no clue what Im even doing ngl
but it will help
if you have no idea what you're doing then you should be following structured lessons on a site like !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
anyone have any idea how i can fix this
how to fix a null at a certain index
and how to fix and index out of bounds error?
assign it or check if it's null before using it.
check that it's in bounds before accessing the array at that index
no thanks
I don't help people over DM
i see
none of them are null, i checked it already
they become null at a certain index