#💻┃code-beginner
1 messages · Page 231 of 1
First one is presumably a field(depend on where it is declared), the other one is a property.
I'm gonna be researching that
Player controller Script
Assuming these files are videos, you should upload them as mp4.
how do i make it not null?
Share your !code properly as well:
📃 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.
Hey guys! I was following the create with code begginer series by unity, I am in Unit 3, in the game the player avoids obstacles running through an endless forest. So obviously the background is supposed to be moving and the obstacle moving and the player stays still and jumps to avoid the obstacles. But in the scripts when I try to call the game Over function to stop the background and the obstacle the player movements Instead Of move left script the player stops jumping and the obstacle and the background keep on moving. pls help. Here are the scripts and the videos discord link to the above messages
#💻┃code-beginner message (expected Version)
You don't need to repeat your message. Just share the code properly
like that ?
how do I share it better
Check the bot message before your previous message
where is it
Presumably, yes. I don't know what script that belongs to, so it might be wrong.🤷♂️
Hey can you help pls
with the problem
i changed things because nothing worked
Mmm... Not exactly what I meant. Don't you have this script on each of the buttons?
I'm waiting for you to share the code.
each button calls a different function
Then you only need one field for the button on the script
but i don't want that at the end
Good morning, I'm finishing my first game. But I'm stuck on something that should be simple but I don't know how to do it. my boss summons these demons. However, if you die and try to press restart the game crashes, from what I think, it's because the demons are trying to follow the player, but the player is dead and has nothing to follow. How do I not have any more summons when the player dies? I will send the link to the codes below. demon controle; https://paste.ofcode.org/Wf8QGE6PrVX5AFQNX9ufNP player; https://paste.ofcode.org/RDJn7EBygswTGacKTiaxgQ boss; https://paste.ofcode.org/r5fYms2KqPpKb3KdNSqpfz
i don't understand at all sorry
i currently have functions that saves a score to an inputted id
{
string studentID = PlayerPrefs.GetString("studentID", "");
// Save total score
string totalScoreKey = $"TotalScore_{studentID}";
PlayerPrefs.SetInt(totalScoreKey, playerScore);
PlayerPrefs.Save();
and displays it in a different scene when the id searched for matches a saved inputted id
string totalScoreKey = $"TotalScore_{studentID}";
int totalScore = PlayerPrefs.GetInt(totalScoreKey, 0);```
it currently works but if the same id is inputted multiple times, the data gets overwrriten, but i want to display all attempts scores, how do i account for that?
anyone?
@teal viper
https://paste.ofcode.org/h3QhJZSKZuwiYw7NBiY8aq
Player COntroller
https://paste.ofcode.org/qFz6fZyzy5nWapxKKDux6M
Move left
Having a bit of a moment, but how can I get the current rotation speed of an object? I'm using transform.Rotate to rotate the object.
Something like this:
Object with script and button 1
Object with script and button 2
Object with script and button 3
etc...
Each object would have a script that references the corresponding button. And in the script:
[SerializeField] private Button myButton;
void MethodToCallFromButton()
{
DoSomethingWithThisButton(myButton, someBool);
}
Makes sense?
a bit...
you need to instead of saving an int, serialize it as a json object and save it as a string. then when you read the playerscore you deserialize it to your json class and read the scores, if that makes sense?
that way you can easily and readibly create a list of previous score attempts
i create 7 emptyobjects, i attach my script to them, and i attach a different button to them ?
If you look at your second video carefully, you'll notice that isOnGround stays false. That must be why you can't jump anymore.
Assuming you want 7 different buttons, yes.
i have a really dumb question but i want to know how to select the frames from animation like this?
the part i don't get is how to i define the action each button is performing
but the guys code is same as mine, the thing does it automatically with code
does this work if i only want to display one score at a time, then use buttons to see previous/next attempt scores?
Assign each object's script and their method to the corresponding button.🤷♂️
Share a link to "the guy's code"
is what call a method ModificationCase() for example ?
it should yeah, this is just so you can save and load the data. you would need to cache the data somewhere if you wanted to repeatedly read it, but thats up to your implementation 🙂
anyone?
thank you
doesn't sound liek a code question? delete and ask in #🏃┃animation
np. just read up on json serialize/deserialize, then you can save larger data sets in playerprefs easily. might have to clear your prefs if you change the structure of the class though
i did but it's dead i just want to know what the shortcut key is please
actually pass in a list when you call the method
I really don't understand what you're saying. Can you translate what you're saying from your native language to english in google translate?
i mean if you know then tell me
What's the same thing?
method and function
he's asking if Methods and Functions are the same thing
or is method a line of code like Debug.LOg
Read my example that I shared earlier. I even named the method such that it makes sense:
#💻┃code-beginner message
Oh, are you asking what a method is?
A method is the same thing as a function.
ok thanks x)
yes, they are the same . . .
so i create a different method for each button right ?
Please use puncutation, because it's not even clear wether you're asking a question
sorry
@frigid flume the be politically correct: the difference is, a method is a function associated with a type (in this case, a class) . . .
button1 on object1 => Script on object1 Method() => Method(parameters referenced in this script)
button2 on object2 => Script on object2 Method() => Method(parameters referenced in this script)
button3 on object3 => Script on object3 Method() => Method(parameters referenced in this script)
Makes sense?
i'll try and show you
i am supposed to have 7 emptyobjects, and only one script right and one method right ?
Right
whats the best unity editor for begginer trying to make a 3d fps lowpoly game?
any
unity editor?
get the newest LTS one
ok :D
what addons its just a singleplayer if there is a recomendation for that?
i just don't get how i can define which button uses which bool
what xd
Performance question
I need to use collision.gameObject.transform.position several times in my code
Would it be more efficient, creating a Vector3 variable inside OnCollisionEnter, to store collision.gameObject.transform.position
And then simply referencing it
Well, define the bool in the inspector as well.
Make it a serialized field
idk what is called or is it modules?
just read it
and see what you need
if you want android support
then use it aswel
what's hard about it?
idk i wanna know if like any of that stuff is like good to have
it has to be loaded from Json
Then load it from json and pass into the method.
You should probably serialize them as an array of bools. You know arrays, right?
position is a struct; every time the value changes, you must get/retrieve the updated value. reference the transform and use the reference throughout the class, though, i would store the position in a variable at the beginning of any method(s) and assign the final position back to transform.position . . .
If you have an array of bools, you just need to do:
Modificationcase(button, boolsArray[myIndex]);
And define the index in a serialized field.
thx a lot,
by the way, would you recommend declaring the varable inside OnCollisionEnter, or main?
main? 🤔
i mean right below the main class, where you have all the serialized fields
sorry for wrong terminology
Class variable(field) vs local variable
whichever method you access transform.position multiple times, store a local variable of the position, then update it at the end of the method . . .
if you use the collided transform in multiple methods, then yes, i would create a class variable for the collided GameObject's transform . . .
you can assign it in OnCollisionEnter . . .
yeah thats what i mean, would it make a difference if the variable is global or local? (i will only use it inside OnCollisionEnter)
since OnCollisionMethod will be called pretty often i would need to be often creating new Vector 3 variables, which may cause more garbage collection
correct me if im wrong
i'm not understanding how to do that
or would i still need to be creating new Vector3 anyways, since every collision will have a different position
If you need to persist the value, between the calls, then it should be a class field. If it's a local variable, it's destroyed as soon as it goes out of scope(when the method it is declared in returns)
I shared a code example in one of the next messages.
it helped me but i don't understand the json bool part
if the variable only exist within the one method, there is no reason to store it in a class scope . . .
What part exactly? You deserialize your json into an array of bools. Then just use an index to access the bool you're interested in.
Sprite position:
x: -5.68
y: 2.47
Parent position:
x: 1.78
y: -1.09
when I get sprite game object position gameobject.transform.position I get:
x: 3.54
y: 0.88
Any ideas? I am trying to convert sprite position into world position(so I can position some UI elements)
Those numbers dont seem to match, localPosition gives better results but its still off.
Where are these numbers coming from?
Sprite has scale of 5 tho if that matters?
what kind of objects are these?
From regular objects, not UI
ok and these numbers came from?
Show the code
and show the scene and what you are confused about
I want to get this number into UI so I can show UI on top of the character sprite.
The inspector shows local position, relative to it's parent
which number?
the one in the inspector here is localPosition
.position is world space position
Yes, I tried to calculate normal position using parent offset and the math doesnt add up
what do you mean by "normal position"
localposition - parent I guess
if you want the world space position of a GameObject that's just Transform.position
if a make an array of bool, its a list of "true" or "false" with no names right ? just a number associated ?
oh
You don't need to calculate "normal position" that's just .position
Yes.
So there is no need to do
Camera.main.WorldToScreenPoint(startPos);
If I get .postion
wouldn't that be tricky when i'll have more than 7 buttons ?
accross different scenes
No. It would be convenient.
It would be tricky if you had to hardcode every bool(like you do now)
The entire point of using a collection is because you can expand it
Vector3 targetPosition = CharacterAnimator.gameObject.transform.position;
Camera.main.WorldToScreenPoint(targetPosition); // When I use this Vector to create UI it appears at an offset
ok found the issue
I was using localPosition on UI
At this point I suggest going through C# basics and unity !learn beginner pathways:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
transform.position = Camera.main.WorldToScreenPoint(startPos);
This works so far, I knew something was up since it worked earlier, but I was messing up with the code and things didnt work anymore 😄
what i don't understand is to define an array using already existing bools without modifying their values
You do modify them. Either load from json or set via code.
You can do whatever you like if you code it
Setting manually in the inspector is an option to, although it becomes unfeasible very fast.
anyone who canhelp me with some photon pun bug?
Photon are you sure you want to go that route?
wdym?
transform.position = Camera.main.WorldToScreenPoint(startPos);
Vector3 currentPos = transform.position;
float randomX = startPos.x + Random.Range(-0.2f, 0.2f);
transform.position = new Vector3(currentPos.x + randomX, currentPos.y, currentPos.z);
Anyone would change anything in this code? Am I doing it right?
I cant seem to find a better way to change x or y of a transform without having to do new Vector or writing a long line of code.
As far as i am aware you pay quite a bit for ccu for the dedi servers
You can always try unitys networking or even go with fishnet if you want
allright i will look into that
i also have question for you because you seem to know a bit around server side, is it diffucult to setup your own dedicted server for a game using like an old pc or anything like that ?
Not at all,you can always do peer 2 peer througj a relay or go through the pure dedi server one,plently of free online options available
The main issue is setting up your network to allow connections from outside. Most home internet providers make it difficult due to dynamic IP and other issues.
but its possible to do if you watch some tutorials
To a degree. Not something for production where you expect hundreds of people to connect to the server.
You'd also need a way to share the ip address of the server with the users if it's a dynamic ip.
yeah but like a small server for like my friends?
how do i define which index of the array has to be used when button's clicked
Yeah, should be possible.
thx
Define that in the script that comes with the button. Or pass it from the button itself.
i got there https://hatebin.com/rmcrdcghan
No clue what's going on in that code. Your button method doesn't seem to do anything. And you're not passing a bool from an array into it.
for the moments it's useless
there is no more bool only a bool array
what i tried to do is to assign an int to each emptyobject so it's used to pick the bool from the array
Yep, that's correct, but you're not using it in the method to be called from the button.
works a bit
almost perfectly
thanks a lot for your help and sorry for the dumbbeing
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
highScore = PlayerPrefs.GetInt("highScore");
Debug.Log(highScore);
if (highScore < 0)
{
Debug.Log("High Score is below 0!");
highScoreText.text = "No Scores Currently";
}
if (highScore > 0)
{
Debug.Log("High Score is above 0!");
highScoreText.text = "High Score: " + highScore.ToString();
}
}
All of this code is working, but for some reason the highScoreText.text is resetting to the default value of No Scores Currently despite no other code interacting with it in the program. Any idea why its doing this? Also highScoreText is a TextMeshPro if that helps.
highScoreText in this code refers to the field in the old instance of the scene, not the new scene
Restart Game should do nothing else than loading the scene
That's bound to lead to bugs
How would I go about changing this?
Put the code that prints the high score into a Start method of some object in the scene
Gotcha
Nice screenshots. You gonna tell us about them?
Lol
🤷♂️
what kind of information you want
sorry my grammar is weak if any problem
What are you trying to do?
Because right now it says public Private MethodScripts privateMethodScripts struct Glyph...
Do you want it to be public or private?
Btw I recommend setting up your IDE to show you the compilation errors
And some good starter C# tutorials are pinned
The code is just nonsense
How would you recommend that I save a pre-fabs position so when I quit and reload my game, they are in the same position with the same information.
Are you trying to modify TextMeshPro source code?
You will have to serialise that object
This fixed it, thanks a ton!
Using game saves
Yes I know. Just like I said, take a look at the basics of C# first
That member header is nonsense
There is a LOT wrong with that code
What is your goal with that code?
Any material about game saving should answer that
You have posted that already.
Use your words to describe what the code is FOR. Right now, as they said, it is nonesense. It is completely wrong in many ways. It is impossible to know even what you are ATTEMPTING to do, so you need to explain before we can help.
Sorry
Oh, I see you DID make one small change. It is not enough to fix it, bit it is a step in the right direction
I was looking into player preferences but I don't think that will work as the pre-fabs would just overwrite each other's data
Configure your !ide and then come back with your question
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
can somne help me the error is NullReferenceException: Object reference not set to an instance of an object and is on the line with GetComponent
Configure your !ide and then come back with your question
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
JsonUtility is useful for serialising game saves
I wouldn't recommend using PlayerPrefs for game saves either. Saving is basically collecting the data you want to save, running it through some serializer library and dumping it to a file
I'll take a look
Give us the exception stack
As soon as it stops working and returns no data on serialization consider using Newtonsoft instead. JsonUtility is very old and has a ton of limitations which prevents it from working correctly.
Basically it means somewhere you are using the access operator ., its value is null. Since it doesn't have a value, you can't access anything
I change some code
@burnt vapor ❌ ? :D
Configure your !ide before asking questions here please
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
It's not a good idea to help somebody who does not have a properly configured editor. Have them configure it first.
Yeah I was confused by that. A stack trace is important
So found this online... Looks like it will work well. What script type would I want this to be on? And why is "File" invalid
Helping them mostly just ends them up with them solving the question and still using a misconfigured editor
It's probably not imported
using System.IO; on the top of your file. This should be done automatically, or when you use "Quick actions"
Thanks that worked 👍
So I'd Just want to call Load Player on start, and save player on application quit?
What fresh hell is this
is that the general basics?
In Rider I can configure the file to import files and lint automatically on Ctrl + S, maybe that works on your IDE too :) Helps a bunch with producitvity
I am trying to add multiplayer to granny chapter 2 and only i and my friend play thes modded verson
I have no idea what you are talking about, but please configure your editor for the third time
Modding is not allowed to be discussed here
What
ok
Also would you recommend I have a master save script, or have this on each of the major scripts?
I would create a FileManager to store all variables you need to store, and provide access to them to other classes
So how would I do this for Pre-fabs?
Would you create some sort of loop that gets all the pre-fabs, and sets them all as seperate data sets, then when loading I can just re-instantiate them
I could get all the pre-fabs, add them to an array, then go through the length of the array saving them?
I have a script that basically rotates cards, moving the leftmost to the right and all others one position ot the left. I get huge GC Collection Spikes when I call SortCards(). Can someone tell me why?
I was thinking it might be related to a big amount of new Colors being generated in MakeCardAppear / Disappear?
Profiler
starting too many coroutines, at first glance
hey, do you know why is that happening ? it's like only one bool is saved...
the code : https://hatebin.com/lqzvqftutb
the problem : https://youtu.be/44qBRIKAYQU (the button is supposed to be green when bool is true, and red when bool is false. it also change color on click (the bool changes too).
Do you want another screenshot of the Profiler?
That's a whole lot of GetComponent calls. You're spawning multiple coroutines, that each spawn multiple coroutines, that each call GetComponent multiple times
have you looked at the profiler when you run the function to confirm?
Would this be a good way of saving pre-fabs, if so, how should I go abouts doing?
There's more than one image, Discord thumbnails messed up
ahh yes myb discord funny
I don't know what you mean by "saving" the prefabs
Why all the finds just drag them in
What are you trying to accomplish here?
That would only save objects with Legendary tags. Also you're not saving prefabs. Any object on the scene is no longer a prefab
Well they all hold information in which I need to save such as level, tag, and other variables
But they're prefabs. They're already..."saved"
Still have no idea what you mean by saving them
they're assets in your project
Based on the earlier questions, they're just trying to implement a bog standard save/restore system
Right so, My breeding script instantiates in a new creature which holds a data set. When I reload the scene, I want that instantiated pre-fab to re-instantiate containing the same info it had
Are you trying to remember which items your player has?
them calling the instantiated objects "prefabs" is the confusing part
So instantiate the prefab, then change the data on the object you've made
I doubt it but have you tried commenting out certain parts of code?
@burnt vapor can you help me now i done every thing
You will need to serialize the data that you need to remember.
This is the info on the pre fab
It could look like this
[System.Serializiable]
public class EntityData {
public int level;
public string name;
}
I have now commented out all coroutines besides MoveCardToPosition. There are 4 cards, means there will be 4 coroutines of MoveCardToPosition running. I still have the same GC Collection issue.
What does this allow me to do??
You'd store the data you want to remember into an instance of EntityData and serialize it with JsonUtility, then write that data to a file.
you could also just store EntityData somewhere and use it later
ohh
You'd then write code that reads EntityData to configure your entity
That's the gist of serialization and deserialization
Turn your runtime objects into data
@small chasm Do NOT send unsolicited DM's to people in this server
Then turn your data back into runtime objects
so each pre-fab can call public EntityData data; then all write their data to that?
Each instance in your scene would be serialized
public EntityData Save() {
EntityData data = new();
data.level = myLevel;
data.name = myName;
return data;
}
public void Load(EntityData data) {
myLevel = data.level;
myName = data.name;
}
It could look like this.
Or maybe more like
public void Save(EntityData data) {
data.level = myLevel;
data.name = myName;
}
public void Load(EntityData data) {
myLevel = data.level;
myName = data.name;
}
I do this in my game. Someone else is responsible for creating the EntityData when saving
I wonder if it's just the coroutine itself getting GC'd? I'm not sure if you can avoid that and still use coroutines. Other than the GetComponents I don't see anything else that could be taking up a lot of space in memory
GetComponent only thing strikes me weird as well
can somone help me
muscagame is null
muscagame is null.
avoid .Find at all costs. Its too frail/slow
Right so this is for saving it. Then how do I store the data? Little confused
can someone good with unity save me from having a mental breakdown
How much garbage are you generating per frame? Look at the "GC Alloc" column.
Hello there, I'm planning to create custom events, should I use my own event system, or Unity has something for that?
send you?
typo
0B 🤔
c# events
Unity has UnityEvent you can create custom events too
At the top.
GC.Collect is going to have no garbage
54.8 KB
https://docs.unity3d.com/ScriptReference/JsonUtility.html
Create a class that'll hold all of your save data.
[System.Serializable]
public class SaveData {
public List<EntityInfo>
}
You can then use JsonUtilikty.ToJson to transform this into a string, which you can write to a file
If you don't need to save data between game sessions, you don't need to do this
You can just store your save data anywhere (maybe in your "game controller" class)
gotcha tnks, is there any site where i can look for examples and documentation bout this?
i cant get the enemy to damage the player on collision, on debug there deffo colliding and ive also set up p as the key to test health loss... both work just not together
Alright, Thanks
love ya
you might want to share some !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.
right ill drag and drop the scripts 1 sec
no, read the bot message
- did you remove the getcomponent calls? they could be allocating frogloads in Editor if component not found
- have you tried deep profiling? it can't get more clear about allocations than that
- yes, I removed the MakeCardDisappear / Appear methods altogether.
- will try that now
one more important thing: you need to respawn all of those entities, right?
so you'll need to save an ID that you can then use to figure out what to spawn
You could give each prefab its own ID and then make a list of all of your prefabs
[System.Serializiable]
public class EntityData {
public string identifier;
public Vector3 position;
public int level;
public string name;
}
your save data might look like this now
Hi, is there any method that allows you to read all files in folder? (Im using Json files to say stuff)
Loop over all files in a folder, and read that file
Okay thanks
Yep
So I've got a script with this. Can you give me an example of how this would be called to save and load?
!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.
Yep
This is what I've sourced from the internet, But I don't know how im creating the sets of data from the prefabs
I don't know what prefabs have to do with this
This is what I've got from @swift crag But not sure how I call this?
you'd write the json to a file to save it. You'd read the json from the file to load it
@amber nimbus I think your first attempt at code was formatted properly but I didn't get a good look at it
Oh ok, I'm gonna log off now and try tomorrow, thanks for the help
Vector3 lookDir = target.position - transform.position;
lookDir = Vector3.ProjectOnPlane(lookDir, transform.right);
Quaternion rot = Quaternion.LookRotation(lookDir, transform.right);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, gunSpeed * Time.deltaTime);
Hello, working on a game and I have this code, what I am trying to achieve is to use the RotateTowards() method, but rotate the object only around the X axis, what I did here does not work at all I was just wondering if anyone knows a way to do this :D
So you want a rotation about the X axis, being the "pitch" axis in this diagram, right?
Correct
Does anyone know why I’m getting this error? And sorry it’s a picture and not a screenshot I’m working on a school computer
learn how to write switch statements
This work is in another script I have for my bullets and enemy’s so I’m wondering why it’s not working here. My enemy and bullets die on contact but I want my player to lose health
big doubt, that code will not even compile
But it does tho
also yout !IDE is not configured, do that before asking for more help
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
Still trying to internalize this a bit how this would look. So, if the targit is above and behind the object, you want it to angle up, but not rotate towards the object, right?
Like, if this object is at 0,0,0 and the target is at 0,5,-5 you'd want this object angled up 45 degrees continuing to look forward?
Because everything was working until I added what I just showed
Yes because that's an invalid switch statement
why do you have a switch statement with one condition
Because it worked for my bullets and enemy’s so I thought it might work for my player. What should I use instead
an if statement
It is a tank gun, meaning the turret rotates around the Y axis (Yaw) and the gun only rotates around the X axis (Pitch). The turret is working with the code above (If u replace the transform.right with transform.up)
Show the other script where it works
Okay, so it's rotating about the X and Y axes, that makes a bit more sense.
These are the working ones
Yes, but the gun object needs to only rotate around X
Once I changed it to an if statement I just get 3 expected errors
And you don't see any difference when comparing to the one that doesn't work?
Well I’m using a break there. But I’m just trying to use my damage script so I don’t know why it wouldn’t work
Okay, so the Y rotation is handled by something else, so you just need X for this object
Exactly
What do you think break does?
"Everything's the same except for the thing that makes the code work so why doesn't it work when I remove that"
also don't use switch statements with one case, use an if
Can you guys actually try and help me instead of criticizing what I’m doing. I get you guys do this for a hobby/job but someone’s who’s new has a hard time learning this stuff and when people just basically call you stupid it makes coding not fun
We are trying to help you
It was a serious question. If removing break makes the code not work, a) what do you think break does and b) why did you remove it and still expect it to work?
nowhere did anyone call you stupid...
Well I get that break breaks that game object but I’m trying to get my take damage to work when the player collided what code would I put?
You need to go through a basic c# course, thats all
break is a keyword
break will exit whatever loop or function you’re in
Okay hang on I'm trying to think this out, I've gotten halfway through describing it like five different ways before I realize it won't work and deleting it
it’ll just not execute the rest
... "breaks the game object"? What?
Oh so I was getting it confused with the destroy?
Its all good thanks for putting the effort in you are a real one :D
I meant destroy I was getting destroy and break confused
Please do one of the basic C# courses linked to you. You need to understand the words people are telling you in order to receive help
Alright but can you tell me why I’m getting this expected error?
What do you mean "expected error"
It says that it need a bracket there but if I put one there’s an uneven amount and everything in incorrectly bracketed
this is hella wrong
Configure your !ide and stop making basic spelling/syntax mistakes
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
neat language what is it
Okay, I think what you want to do is to use LookAt but with a constructed target point instead of the target's actual position. I'm trying to come up with a formula for getting a point at the same relative height and distance, that's what's giving me some trouble
Can't just get the LookRotation vector and zero out Y and Z, because there's no guarantee the euler angles of it will be in that exact form...
Looking at the documentation for a switch statement would immediately reveal what is wrong
A configured IDE would immediately point out what is wrong
A configured ide is a requirement to get help here
But ONE issue I will point out is that you have a semicolon at the end of the case line
I think that's the smallest issue here
That's why I chose it
If he doesn't understand what he's doing
Okay, I think I have an idea.
Get the vector from this object to the target, target.position - transform.position.
Then, set that vector's X to zero, and the Z to absolute value of Z (this will avoid the turret looking behind itself)
Then you should be able to use LookRotation with that vector, and set this objects .rotation to that Quaternion
Misping @umbral gazelle, sorry this was for someone else
@amber nimbus ^ this was meant for you I think
It was I'm sorry
Mis-reply
#💻┃code-beginner message
when ever i underline somtething to delete a line or anything the mode from insert gose in , inlite proposal i think is called. How can i disable it?
...what
press insert on your keyboard
im still working on a player interaction system but have run into an issue where when i want to drop the item, i have to look at the untagged ground. and even then it gives me an object reference error and doesnt drop it
// PICKUPABLE INTERFACE DECLARATION
if (Input.GetKeyDown(KeyCode.E) && interactObj.CompareTag("Pickupable") && isHolding == false)
{
Debug.Log("pickup");
isHolding = true;
interactObj.GetComponent<IPickupable>().Pickup();
}
else if (Input.GetKeyDown(KeyCode.F) && isHolding == true)
{
Debug.Log("drop");
isHolding = false;
interactObj.GetComponent<IPickupable>().Drop();
}
Press insert on your keyboard
i have to press it like evry 3 secons
Then maybe your keyboard is faulty
ok thanks
You probably want to store the last IPickupable you were interacting with, and then call .Drop on that instead of the object you're currently looking at
assuming interactObj is something in a collision or raycast
yeah interactObj is set as a gameobject the raycast touches
ill try this
Oh yeah that works great, thanks :D
I have no idea have you came up with that
would that require a variable inside IPickupable?
Currently trudging through some code reorginsation to implement something new and I've basically had to go and redo most things in it, it's structure is really not ideal. Are there any places to get some kind of code review to see how I could restructure it? It's not looking good and could be so much better, but I'm not too confident on what could be changed
here
I feel like chucking it all in here would be a bit much
maybe there's some particular aspects which are frustrating that you could call out and focus on?
Unless I sort of abstract it into ideas rather than every single line
theres a chance that maybe someone will take a look at it. if u dont post it then theres no chance of that happening at all
I’ll see what I can do
Yep, if you can share the broad strokes that's sometimes enough. Generally though you may struggle to get much useful advice here on something so in-depth (but it depends what you're working with)
Honestly me neither that was actually a surprisingly difficult problem
would that require a property inside IPickupable?
which has the correct syntax highlighting? and why are they slightly different?
No, it'd just require whatever object this script is on to keep track of the last IPickupable you interacted with
There isn't really a "correct" one since you could always change it but the second one looks like it's got any syntax highlighting at all which is probably better
this script is on my player camera does that matter
how do you change the syntax highlighting, cuz in all of mine now i have "using" in blue but in a screenshot i took last week its purple and i prefer it that way
!ide
Oh is the bot broken?
Not really
i swear ive done that already
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
What the-
Was trying to write it out but I can't find a feasible way to explain it. The way I've done it is rather convoluted and has so many connected parts. Essentially it's an inventory system with three types, but each type has methods that themselves take different types and do different things, and item containers that are also different types. Each of them has a container, and methods to add / remove items, but I've got them all separate, and I don't know what I could do to have them all a bit easier to follow.
I've tried having a superclass they all inherit from, but then if I call .AddItem or whatever on that super, it won't work since the methods are different for each and the types are different for each
it will fail at runtime
That compiles. But it's definitely not gonna run
C# won't know that's nonsense until it tries to actually do it
if I call .AddItem or whatever on that super, it won't work since the methods are different for each and the types are different for each
wdym by "won't work"?
What part doesn't work
what are you trying to do that won't work?
Did he even send code or smth?
did not send code
because T is generic and takes any type, doesn't mean the function will work though
shouldn't that at least give you warning being non-component in console
That's the thing, if I go into it i'll be spewing pages upon pages. I'm trying to find an easier way to describe it but I can't really pinpoint it yet. It all stemmed from me wanting to change something but it's just messy at the moment
I didnt check
just ignore me for now, I'll try and get something more concrete
Well the details are important. Right now it's pretty vague. At a high level let's say you have three different items. Maybe one is a potion, one is a sword you can equip, one teleports you home. If you are doing an inheritance pattern there should just be an abstract function called Use on the parent class, and each subclass would implement Use in its own way. For example the sword would equip itself to you, the potion would restore health, and the teleporter would teleport you.
that being said inheritance is not always the best architecture
composition is often better
how does that differ?
so an item could instead all just have something like List<Effect> - where Effect is now an interface for example or abstract class, and every item you just loop over all its Effects and apply them
Or Effect is a delegate type
pointing to different functions
Hello, I have been struggling for a week now, to which seems like a simple thing.
In my 3d game, a character will move on a 2d plane and interact with 5-6 unmoveable gameobejcts.
I can not figure out if navmesh agents is best way to move the characater, or handle movements myself .I have tried both and face many problems in both approach . I do not need physics.
Please guide, which is theoritically better .
there could also be other things like giving them a List<UsageConditions> which you loop over to determine if they're currently usable
Your question is too vague
It depends on what you are trying to achieve
and "handle movements myself" could mean almost anything
Why not to just combine? Nav mesh is mostly made just for finding path
I agree . When user touch a gameobejct, character will move towards it and "interact"
When user touches an empty space, character will move towards, while finding best path, avoiding gameobejcts.
sounds like navmesh is perfect then
Collidiers are creating issues. agent becomes jittery after collision , position and rotation keeps on changing 0.0x
you can always use the nav mesh to do pathing and then move along those paths using your own movement in wahtever way you want
do your obstacles/objects have the Nav obstacle on it? Put it on carve mesh mode
if you need pathfinding you either use navmesh or implement a known pathfiinding algorithm like A*
also is it a grid?
not a grid
NavMesh is probably the simplest way to start
sounds like you should navmesh it up
i do not know carve, i will checkout
I usually use carve when the obstacles rotate or move, might be overkill but works well for my agents
so like this?
all ur obstacles should be carving empty spacing in the navmesh
he'll automatically find a path around them
If for example I had a StructuresInventory that had AddStructure, and an itemInventory that had AddItem, both inheriting from Inventory, if I were to pass in just Inventory elsewhere, would that not be able to perform either methods from those other two inventories? only the methods from Inventory itself?
How do I can use the Collision2D variable of OnCollisionExit2D in another method?
pass the reference
store it in a Collider var or something
or pass it through method params if you need to call it right away
do they even need special methods? also abstract methods exist
yes similar, and simpler. thanks for demo
Okayy thanjk you
In this case, yes, since they all would take in different arguments and have different ways of adding them
is it trouble-some to use colliders+rigidbody with navmesh ai ? Can they mix
depends what you're doing
I would question whether an inventory would really need unique behavior for those aspects, or whether your inventories can be simpler (a list of ids) and the complicated handling happens when the items are actually used or whatever
touch to move and touch to interact, only therse 2, on a mobile 3d game
not sure why you need rigidbody for that
the navmesh is moving the transform and it conflicts with rigidbody movement,
You can put a locked /kinematic rigidbody for example to push other rigibodies though
!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.
rigibody is to figure out if the interact has happened. oncollision .
I am not using any physics of force
well you don't really need that, you could just use Physics. class
Raycast, Overlap, Casts etc.
can someone help me , why is there an error at the set function https://gdl.space/ahayafibim.cs dont understnad what this means
I do sort of have an ID system in some parts. For instance all the items of the 'Processed' type have a database where each item has an ID, but all of the raw items are unique and user generated in a way, so they can't simply be ID'd, if I get what you're saying
Ok. I did try Raycast to find how close the two objects are and decide "interaction". but there are multiple gameobejcts close-by, and may be my maths is wrong, but raycast wld pick wrogn object based on transform.forward
Even if the item is unique, the whole item doesn't need to actually be in the inventory -- the inventory could still just contain the id and then the items contain their functionality. That way your inventories are dumb and only the items are smart
you are trying to set on a prop that is private
you can only set it from inside this class
also sometimes raycast maybe too thin, there are other methods like boxcast, spherecast etc
maybe your forward was wrong, could be many things. Best way is to just debug instead
Your items should probably exist somewhere on their own and be interacted with directly. The only thing an inventory is is a list of item ids, which you can get one of, resolve to the item, and do stuff with.
Thank you everyone, @rich adder , I will attempt as suggested .
so is the solution to make it public?
Makes sense, but in this case that'll be an ever expanding list of IDs
if that's what you need
why do you want to set it from outside ?
sounds like maybe that's not an inventory though, since inventories tend to be limited in space
maybe you're doing something more specific and complex but you'd need to explain that
cant you make a single Inventory class and then do Inventory<Structure> and Inventory<Item> or something
just do
public bool isMoving => _isMoving
if you want to read it from outside but private set, and use _isMoving to set it
also this should be
_isMoving = inputMovement != Vector2.zero
not ==
generics are useful if you have different things which are handled similarly, whereas this is a case of different things which are being handled differently (but i posit that they don't need to be)
but my game is 2d so shouldnt it be vector2?
yes use vector2 because its inputs
nothing to do if game is 3D or not
If I can find a way to simplify it then I'd love to. But since inputs into the game come from photos taken by the user, which then acts as an item, I don't know how that could incorporate an id system when there isn't any knowledge of what that item could be beforehand
Unity uses both interchangeably
true they should be handled the same way cause both are inventories, just with different types of items
ohh ok thanks
whats the id system needed for?
Well I was just going by what Prakkus mentioned. But my understanding is just that an inventory could hold just a number which then refers to an item elsewhere
the inventory can hold the item itself, and you can create 2 instances of this Inventory class, one contains structures and the other contains items
Inventory<Item> iteminventory = new Inventory<Item>();
what do you think about this
i'm not sure i understand, cause no matter what the user gives you, you probably want to build that into something your game will use, which you will have full control over and can id or reference however you want
Hey guys
Using timescale to pause game but the camera still rotates during pause
Not through input, but through momentum, so if I pause before I do a mouse swing, it will still rotate
I am using Cinemachine, anyone got any tips as to what I can look for to solve this
In that case I'm probably the one who isn't following properly
Inventory<Item> iteminventory = new Inventory<Item>();
Inventory<Structure> structureinventory = new Inventory<Structure>();
there's your two inventories and they both use the same class, named Inventory
and both use the same method for adding or retrieving items, just with a different type
by using T
aka generics
Haven't used them all to much. Some people have recommended me not to but I'm not 100% sure on their best use cases and implementations
I'm definitely going to try and draw up some diagrams later
reset the values to 0 when game is paused
timescale only affects things that depend on it
heres a unity tutorial on them https://learn.unity.com/tutorial/generics#5c8923c5edbc2a113b6bc335
and u can have a method like this in your Inventory class:
public class Inventory <T>
{
List<T> items;
public void AddItem(T item)
{
items.Add(item);
}
}
and any things specific to structures or items you handle in their own class
Can you have it so that you can perform a specific set of tasks depending on the type of the input?
so i have an issue where, when my character runs in a straight line they randomly stop, kinda budge around on the y position, despite the ground being entirely flat. im using a box collider with unity3d (my 2.5D game) and im curious how i can stop this?
Yes. You can do anything. C# is turing complete
That is also... the most basic thing you do with Input
Do tasks based on type of input describes all user interaction essentially
what is the ground made of
i used a tilemap, using box prefabs with materials on them
so separate colliders?
indeed
the issue is the edges between the colliders. Use this to merge them into one big collider https://docs.unity3d.com/Manual/class-CompositeCollider2D.html
if you want then this is possible:
if (T is Structure) {
}
else if (T is Item) {
}
this'd work for my 3d cubes collision?
3d cubes? No I thought you were using 2D colliders since you mentioned tilemap
oh no mb
Is there a reason you need 3D physics?
i was thinking that as well but if he doesnt want to inherit his structure and item from the same base. do interfaces work here?
You could use 2d physics
Interface or abstract class would be better here yea. You would simply just call 1 method, and each class would implement it as they want
are you using character controller maybe play around with skin width @dusky dirge
3D physics doesn't have as good of a solution for this problem
you might have to use a mesh collider
and potentially generate the mesh dynamically
yeah i would definitely use an interface here. i didnt say it because i was unsure if you could use these here
interface called IInventoryItem and put it on both your Structure and Item classes. @hidden sleet thats probably the best code you will have if you do it this way
then you need zero if's as well to check their type. cause you just call the interface's methods
(generally for items I think composition > inheritance... but I don't know much about the discussion at hand 😄 )
i looked at night 5 AM and saw nothing, went to bed, just checked now and yes i did.
it works now, thanks for yalls help
idk these terms, whats the difference between these two? 😅
Still trying to wrap my head around how it is different to inheritance. It was brought up earlier but it's the first I've heard of it
inheritance is abstract class and composition is interface? or what do you mean
inheritance is a hierarchy of classes
problem is that at some point you need something to be both a StackableItem and a SomethingEleseableItem (Weapon or something 🤷♂️ )
why not bolf?
composition is... you have a single Item class, and it has different components that handle different aspects... you add Stackable component and that handles the stacking aspect, you can put it on an item that has the Weapon component, Damage component, Whatever component
Interfaces might make things awkward. With interfaces or abstract class, you inherit some functionality. Anything that has this component will have to use that function. With composition, you just attach stuff that does what you want. If you dont want it, dont attach it.
public class SampleScript : MonoBehaviour, IStackable, ISomethingElseable
Unity's GameObject/Component architecture is a composition architecture.
You don't have subclasses of GameObject
you just attach different components to make it do stuff
it does tend to be both, but usually it's a shallow hierarchy like interface + a few implementations right underneath it on one level, and those are then composed
yeah, I made a component that searches in the fields in all components on the current GO 😄
there needs to be more resources on the aspect of designing a fleshed out gameobject
i feel i did 100 uturns / circles when i first started learning to combine scripts
still do.
I'm pretty new to Unity, I'm hiding buttons once they're clicked, is there a more efficient way to do this? I got so many buttons, I'm getting confused.
it's because the unity architecture is silly and untenable beyond little prototypes and setting up an alternative is a lot of work
or a lot of work to make tenable
thats how i still do it.. disable buttons / make them un-interactable .. if i can i'll group buttons in empty gameobjects so can i disable them in bulk
what would be a unsilly alternative?
whats silly about it? just wondering
Ahh ok thanks. I'll carry on then
if u need to dont be afraid to scratch out notes / about ur buttons on piece of paper
to keep urself more organized
Yeah I should really do that
I think that's important part of learning and seeing different options... also, in programming in general it's pretty useful to get used to the idea that stuff will need refactoring sooner or later, and to start recognizing when something is starting to be a problem
everything is public...it's a world where any object can talk directly to any piece of any other object from anywhere
we need rules, people
we live in a society
lol, ohh that happens organically.. i havent figured out how to catch it before hand.. but theres always that moment when u stare at ur codebase.. and are like: "well f***, this isnt gonna work"
then u put it in reverse 😄
ahh i see
then again, there's ECS, which many people will tell you "it's the future and the one true way of doing game dev", and there all data is public
🔥 BURN
Bobby explains a lot of the problems well here (timestamped) https://youtu.be/jjEsB611kxs?t=562
A long brain dump about entity/object models in game engines today...
Follow-up on additional questions: https://youtu.be/fuiNOWEUnJ8
Prototype implementation: https://github.com/BobbyAnguelov/KRG
00:00:00 - Stream Start
00:00:07 - Intro
00:04:44 - What is an Object/Entity Model
00:09:24 - Game Object Component Model (OCM)
00:16:54 - OCM: Ref...
the whole video is an overview of the various ways in which engines tend to model entities (including ecs) and some of the pros/cons of each one
ahh okay. i'll give it a bookmark 👍
first he talks about the unity/unreal/etc model, then ecs, then his own opinions on what a good hybrid looks like (but the part i linked is about the unity style)
im on my 2nd year of learning Unity.. and ECS stil feels over the horizon for me
i feel like u need a CS degree to understand how to use ECS
one might say ECS is more organized and simpler
How can I find where this event that I've invoked actually does something? OnItemRemoved?.Invoke();
(Disclaimer: I've not done much ECS though)
find anywhere that has subscribed to it
use find in ur IDE on OnItemRemoved
look for the subscription ^
usually in awake/ start/ onenable
I tried find references but couldn't spot anything
just use Find
actually let me double check that it's actually being used. Will remove it and see
if nothing is subscribing then it's not doing anything
I would agree with more organized, but disagree with simpler. Mostly because you lose the ability to use most Unity components directly. It is a lot more complex
I do love it though
void Awake()
{
// Subscribe a method to the event
OnItemRemoved += HandleItemRemoved; // here is a subscription.. now u know HandItemRemoved() is one of those methods
That's a fair point. It's my main reason to not use it more.
Yeah. It will get there, but it's a commitment at this point
you could totally do 'in scene' ecs where your gameobjects are entities and your components are components and you just structure things like an ecs but i've not really tried that, donno if there's some gotchas
you probably wouldn't get the cache benefits but i'm not sure that matters much and you can learn the pattern
Hello, guys! I have a question. I heard about not using public access modifier very often and instead of public modifier to use encapsulation and get access to some fields. How can I do that, for example if I want to see my audio sources or my audio clips in my inspector which modifier to use if not public?
Cool now you can get the good one and switch to VS
It's just the program. Reinstall it and your fine
you usually want to sub in enable, and unsub in OnDisable. Unless you have a good reason
Or do VS ☝️
[SerializeField] private
That will allow you to use it in the inspector
yeah tried doing it from the microsoft site then i couldnt link it in unity
subbing in Awake makes unsubbing a bit more difficult, since unsubbing in OnDestroy can be problematic as multiple different things might be destroyed or being destroyed
so im just gonna download from unity or whatever it is
Yes but with that private field I won't have access to use for example my audio source on other classes?
Yes correct.
For that you could do a property
[field: SerializeField]
AudioSource source {get; private set;}
i very rarely make public fields. I very frequently make public getters (with private setters)
public setters or public fields is bad juju, since you make it possible for random classes to fuck with your variables in ways you don’t have complete control over within that class that holds it
there is a time and place for them, but it is more like driving without a seatbelt
i almost exclusively allow external modification to fields via a few controlled public methods
Yes but if I have to make a lot of fields public, I have to make for every that field a property?
you never have to make a lot of a fields public
you might need to make some fields public, rarely
the majority of my fields are defined as auto properties
i think public setters can be ok since what they do is controlled by code. public variables accessible from outside a class are pretty hard to justy though
private int x;
[SerializeField] private int y;
[field: SerializeField] public int z {get; private set;}
these are the bread and butter patterns
You mean where the setter is fully defined?
Because I think they meant just set;
yeah i mean public set, public get essentially just gives you a public variable
but public setters that are defined are commonly used
my main rule is that stuff should be set in as few places as possible... unless something is a generic stand-alone parameter 🤔
public setters are very prone to abuse. Let the class that holds the variable be responsible to managing its variables, so it knows how to update anything that needs to happen
that's kinda what a setter is 🤷♂️
yeah that's exactl;y what a setter is
a public setter has to account for basically ANY sort of setting operation that could happen
Ok, agreed with that then
specific methods only need to worry about one thing
i downloaded this thing but its still saying its not there, is there some specific folder i need to put it in?
you tried googling the error?
or what is the problem
ive never seen the error tbh
a public setter doesn't HAVE to do anything, it's defined in code
you can limit it however you want
once you expose the setter, the setter is now responsible for maintaining order within the class, with respect to changing any internals
that's not true, everything inside the class can explicitly refer to the backing field
you can also have properties that aren't explicitly tied to individual backing fields
if mario’s number of lives has a public setter, then that setter better know what to do with a negative number of lives, zero lives, it better invoke SFX, it better tell the UI
but now you can’t separate it easily
So regarding this issue I was having earlier, I've got a better example here. I've got an cs public void UpdateDisplay(RawItemInventory inventory) { method, which will update the elements of a ui to match the inventory contents, but then another one cs public void UpdateDisplay(NewProcessedItemInventory inventory) { for a different inventory type. But since they have different inventory types and slot types, I didn't know how to streamline this cs protected NewProcessedItemInventory ProcInv; public Dictionary<NewDatabaseInvItemSlot, GameObject> invSlotToUiObject = new Dictionary<NewDatabaseInvItemSlot, GameObject>(); , cs protected RawItemInventory Rawinv; public Dictionary<GameObject, NewInventoryItemSlot> UiObjectToInvSlot = new Dictionary<GameObject, NewInventoryItemSlot>(); public Dictionary<NewInventoryItemSlot, GameObject> invSlotToUiObject = new Dictionary<NewInventoryItemSlot, GameObject>();
but you already have methods for that?
then why do you need a public setter
in the end, a property setter is just syntactic sugar for a method
you no longer have a simple way to just change the number, vs change the number and do all the ancillary stuff
I did try just having a base Inventory class, but then I couldn't use the methods in the sub classes even if I wanted to pass in the subs, because I mostly misunderstood how it worked
public int MyValue { get => _myValue; set { /* sexy */ } }```
is your point basically 'if you are doing something complicated when changing a value, you should probably give that operation a name and make it a method, rather than having a complicated setter which doesn't explain its intent'? cause i think i agree with you there
a lot of my public setters with advanced logic turned into problems, separating responsibilities between specialized methods and calling the public setter
right i opened visual studio code once, i closed it and opened again and the syntaxs were different
there are lots of classes in unity that use public setters and there are lots of properties that aren't explicitly tied to individual backing fields. you can also have different properties that change the same or multiple backing fields in different ways
this is a common use case
because now you need to go read through code to see if you are supposed to invoke a method, call the setter, or set the backing field
because unity’s source is effectively sealed.
it’s ok to make public setters, but it can very easily and quickly lead to massive issues
yeah i mean... you have to be smart about how you're designing and using your classes, sure
but that's always the case
You can do literally the same thing with a public setter and method
properties definitely have pitfalls
you can't name the public setter though
if you're doing too much stuff in them and they're the only way to do that thing, that can be a problem
but i'm not sure i'd say "avoid public setters as a rule"
the one true rule is that you should not follow rules too strictly 😄
That has 0 effect on what you can run, yes it makes sense sometimes to use a method but the talk above seemingly was about what a public setter can enforce
fwiw i agree with this - changing variable values in a class should be done in the most lightweight way possible and shouldnt' take into consideration every possible way you could change the value of that variable. i definitely think in many/most cases, using methods that modify state in a particular way is advantageous to exposing a heaviweight public setter
the lesson is;
public variables are like public toilets. Everything is fine until someone shits in it.
lol, i try to make everything private and then make things public as i realize i need to
thats my new procedure im trying to make habit
and I try to avoid making setters public
i would rather write a public method that sets for a specific case. And I am still very strict with my public setters
making a getter public when you realize you need to read it is fine imo
looking through my code, in my current project, i'm rarely using public setters (or any setters at all) but in a previous project i did, public setters came in very handy. in that case, i was making a runtime inspector for modding a unity game through harmony and the UI controls that I made had a class that modified an underlying runtime value. there, how the setters operated depended on what the underlying runtime value was (determined via reflection), and i found that using a setter that did a few simple checks to determine how to modify the value worked well
because the better you get, the more you restrict the ability to set your variables
Additional updates include periodic refresh of inspected values, other fixes to dropdowns, toggles.
like with this class:
/// <summary>This is affectively an Action, where the inner implementation is
/// a list to allow lots of entries to be added more easily.</summary>
public class BigAction {
private List<Action> actionList = new();
/// <summary>Construct big delegate with capacity.</summary>
public BigAction(int capacity = 16) => actionList = new(capacity);
public int Count => actionList.Count;
public void Add(Action action) => actionList.Add(action);
public void Remove(Action action) => actionList.Remove(action);
public void Clear() => actionList.Clear();
/// <summary>Invoke all the actions. Actions can be added to the delegate in the middle, but do not remove.</summary>
public void Invoke() {
for (int i = 0; i < actionList.Count; i++) actionList[i].Invoke();
}
}```
been abandoned for 4 years and nobody cares about it but it was a fun project
i could have made that list public, but I did not, so I could make it a lot easier to track and control.
nothing will randomly sort my list. Nothing with randomly assign to some index in the middle, etc. And that is ok
yes, there are many examples where you don't want a public setter 😛
but lets say this class had some parameter that controls how it behaves... it's quite possible you'd just want it to be a public thing 🤷♂️
say "ClearListenersOnInvoke" bool (random example 🤷♂️ )
as a general rule of thumb, the more things that access an instance of the class, the more you need to restrict access
or very tiny data structure classes probably have a lot of public setters.
probably could have used different classes for modifying properties or fields but... this is what i came up with and it worked i guess
set
{
if (isProperty)
{
currentPropertyInfo.SetValue(currentComponent, value, null);
}
else if (isField)
{
currentFieldInfo.SetValue(currentComponent, value);
}
else
{
throw new InvalidOperationException("cannot set value where member is neither a field nor a property");
}
}
but like this worked pretty well...
Hey guys I have a problem, I'm trying to implement a knock back effect into my game but I noticed that the player movement is overriding it so it doesn't do anything, how can I fix this?
i normally stage movement changes
A coroutine that disables movement
player movement should happen in normal fixed update
modifiers that have to lead into it have to happen before, and things that modify after need to come after
but since player movement is normally followed by physics sim, whether you modify (via knockback, magnet, etc) in collision callback vs earlier in fixed update, it will all be on the same side
eg the order is still: playermovement => sim => knockback
Eh I tough of it, but how can I decide when to enable movement again?
I would like it to be enabled again when the player stops getting any velocity from the knockback
are you trying to block playermovement entirely? or adding a knockback effect on top of the movement
what I described is the latter
I would rather add the knockback effect on top
ok, then what I said
Wait until velocity magnitude is under a threshold
make sure knockback happens at a point in time where you are ready for it
Ehh my english and my coding skills aren't that good so I kinda got lost
- make sure knockback is always applied before or always after playermovement
you do not want the effects to sometimes come before, or sometimes come after. Whichever you pick, it should always be the same
Well the issue is that the normal "get axis" does that if I'm not clicking anything then the value is 0 so it sets the player velocity to 0 and completely stops everything
- avoid setting velocity directly unless you want to override everything that came before
How do I set it NOT directly?
AddForce or related
You can set velocity directly, but use the current velocity as part of your calculation
Read, modify, write
if it is a kinematic RB, then you want to do like a += velocity, as opposed to just hard setting velocity to a specific number
I placed this red thingy directly above. But when I play my game it always skews towards the left a little bit, why?
Hm okay, i actually tried using addforce but it started working in a weird way so I stopped using it.
I'm gonna try again
example;
my player jump modified rigidbody.velocity = new Vector2(velocity.x, jumpSpeed). So it ignores ALL changes to Y velocity that comes before it
but if you .AddForce or do rb.velocity += new Vector2(0,5);
this just adds movement on top of whatever you have
and if your control stick directly sets rb.velocity = to a specific number, then it is overriding everything. You want to not do that
Okay but won't adding force countiously for the movement make the player faster and faster?
it depends on what you do
a knockback effect should be an impulse force. Adds to velocity once, and then done
Okay but I'd need to use add force also for the main movement since I don't want it to override everything
add forces ADDS force to whatever forces are already there
Well but how would I create a script that makes the player move at always a constant speed, but allows for other forces to work
Because the issue is still that even if I add a force for the knockback the player movement just resets it back to the default movement speed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointFollower : MonoBehaviour
{
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializeField] float speed = 1f;
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
I placed this red thingy directly above. But when I play my game it always skews towards the left a little bit, why?
this is kind of contradictory because if the player's input is making it move at a constant speed, then outside forces cannot act upon it because that would change its speed thereby making the input no longer apply a constant speed
but you could instead just not get input for the duration of a knockback to allow the knockback forces to work then after a short duration allow input to start working again which will then override any leftover force from the knockback
of course tuning that timing will be fairly difficult because you want it to last long enough that the knockback takes full effect but not so long that the lack of response to input is noticeable to the player
or another thing you could do, which will be more complicated but likely work better in the long run, would be to create your own wrapper class for a Rigidbody that you interface with instead of the rigidbody. you can then track the amount of force input should provide as well as outside forces then combine that manually and assign the velocity using that combined force. That would give you more granular control over the forces being applied to the body while also letting you keep your input's force at a constant rate
u could keep up with velocity..
construct ur vector before hand and pass it into the rigidbody at the end..
ud have ur movement forces and ur knockback forces..
and u add them right before u pass them into the RB
(this method would allow the knockback to influence the player but u'd still have control)
(for example if u got knocked back.. u would be able to push back using ur movement)
but if u werent holding any controls u'd get the full knockback..
oor u'd have to isolate the vectors and zero out ur movement to allow knockback to be the only force.. if thats what ur looking to do
coroutines do not delay the code they are called from
they only delay what is inside of them
so i just put both code lines changing the text inside of the coroutine?
It seems to be working just fine. It's doing absolutely nothing after exactly that amount of time
!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
how to make scalable positive fire rate
i jus don't get it how to do it without a cap
talking when the fire rate exceeds the framerate?
is there a way to do this without needing to pass a parameter?
This is the only time im going to use this coroutine so it seems kind of useless
so there's a cap when the fire rate reaches more than 60
Instead of using a parameter, don't
you need a loop in the update for that, so you need to figure out how many to shoot in 1 frame, then positon them slightly different within that frame
to figure out how many per frame to do, it will be a calculation based on how many you want to fire per second and delta time
why position them slightly different
Because otherwise all of the bullets spawned "between" frames would just be one big stacked giga-bullet
yeah more or less given the first ones in the frame a head start
well the weapon that i plan on using is not automatic so i don't think we'll need to worry about it exceeding one frame
then what is the issue then
Well, you also wouldn't have to deal with a firing rate being less than one frame
if you are not worried about that problem, its a much more simple problem to solve
Honestly I don't think you'd have to deal with it being less than two frames because in order to press the button it first must be released
well that is how UI is handled, but generally shooting is on press not release
Yeah but if you press a frame on two consecutive frames, would Unity actually know that's two presses and not a hold across two frames?
but if not worried about multiple per frame, its a simple set a field on shot to how long you want to wait in seconds, and per frame subtract delta time, and dont allow a fire again till its 0 or below
Yeah, I'm just pointing out that even if you had zero cooldown you'd still only be able to fire at a rate of one shot per two frames, so there is a cap even without programming one in
its like 20 minutes till dawn if you get me
or isaac
you can hold the button and it spits out a bullet ever 2 seconds or smth
So it is automatic
Why did you say it wasn't
if you want it to require a new press for each shot, but act on the press not the release
oh wait
just use a bool
you're right
So back to the original solution then
release unsets the bool
yeah i could do that
but i don't want it to be so automatic that it does like
5 buleets in 1 frame
Then just don't make them shoot that fast
i suppose thats a cap then
a timer then
but how do firerates even work anyways
make a shotDelay field
have a positive value make another go down
before shotting make sure its 0 or below
when you do make a shot set it to how long you want to wait
subtract deltaTime from it every frame
You set a bool when you shoot, check that bool is false before you shoot, and after a period of time, un-set it
yeah but how do we calculate the period of time
dont evne need the bool
since there are gonna be items that make the firerate go up
yeah that is fine
That's entirely up to you
and im having trouble figuring that out
makes sense
dont fire when its above 0
when you are aloud to fire, you set it to how long you want to wait
then on update you also do a shotDuration -= Time.deltaTime
a variable that is defined on the class not in the function
so like private float _shotDuration; on your class
you guys are based
yeah but how do we calculate that tho
since the firerate is a positive number
and it only goes up
not down
I don't know what you mean
you wnat a firerate that is like 5 shots per second
like it improve the more it goes up
so the faster you shoot the more it is
you just have a shotDuration of 5/60
Then you reduce the amount of time between shots
With - usually
if it goes up by one
But multiplying by a value smaller than one also works
public class Gun : MonoBehaviour {
[SerializeField] private float _fireRate = 10f;
private float _shotDuration;
private void Update() {
_shotDuration -= Time.deltaTime;
if (_shotDuration > 0) return;
if (Input.GetButton("Fire")) {
_shotDuration = 1f / _fireRate;
Fire();
}
}
private void Fire() {
// todo fire the bullet
}
}
something like that, untested but gives the gist
what is fireRate? you might have an easier time if you think of it as shotsPerSecond or something like that
bro i used an Ienumerator 😭 😭 😭
though generally i would not define fireRate like this
like instead of saying 10 shots per second like that and needing to divide
I have this code to change the full screen mode to be that of the a toggle isFullscreen
{
public void SetFullscreen (bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
Debug.Log("Toggled Fullscreen");
}
}
however when i leave it in windowed, close the game, and then reopen it, it will start the game in windowed, but the toggle is still true
i would say it waits 0.1 seconds between shots and skip that division to convert from firerate to delay
crap how do i explain this 😭
its gonna sound really stupid but it's like a revolver that you hold down to shoot...
oh so you want the delay to happen after you press the trigger
you hold down the button and it shoots then waits however long then shoots again without having to release said button
very simlar idea, you just start the countdown after press, then fire wehn its 0
it stops after you releases
how do you reference another float from another script for example, public float sens = 50f;, and in a different script i do if(...) sens = 0;
hi, may anybody tell me why in my chess game this script summons a queen after promotion correctly (1) but when i tried to change it with giving few options to the players it suddenly stopped working (2) The piece is always black and it spawns always on 1 side of the map, not where the pawn was?
show !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.
Yea, i will in a sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointFollower : MonoBehaviour
{
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializeField] float speed = 1f;
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
Does anyone know what this error is? Everything works well as intented but I just wanna get rid of this error !
well look at line 12
and read the error message
its a pretty good and descriptive error message
Looks like the variable waypoints of WaypointFollower has not been assigned.
You probably need to assign the waypoints variable of the WaypointFollower script in the inspector
https://gdl.space/acizifomok.cs working one
I did assign em
https://gdl.space/aziyeqotaq.cs not working one
Okay so show where you've assigned them
that screenshot shows nothing
I assigned them on these thingies right here
Okay so show that
show where you've assigned them
Almost like you shoulda read the error and did what it said
I assigned them on the red box named "Enemy"
And then... I assigned 2 way points in the waypoint script inside of that
have to keep in mind, there can be multiple instances of any given script in the scene
and the reported error might not be for all of them
Anybody knows why?
so should I just ignore that error ?
no
sometimes I get errors like this and then later they go away Idk why
figure out why you have the error and resolve it
No you should fix it
what do you mean?
you have more then one WaypointFollower in your scene
make sure waypoints are assigned correctly on all of them
You have a bunch of objects assigned here that you're enabling whenever a promotion happens. Why? It's going to activate whatever you dragged in, not spawn a new object
I did. They are all assigned
The pawn enters promotion, player get to choose from 4 options as in normal chess via buttons, when he chooses one all other disappear and the selected piece is supposed to go on the tile
Search t: WaypointFollower in the hierarchy
It spawns the piece and disables the buttons but piece alwais spawn in thhe corner and it is always black, when queen from first script changed colors and were on the same tile as pawn
floor (4) had one as well. I deleted it. Not sure why im still getting these errors though
Did you clear the console and run it again
Did you clear the errors and ru- ah, too slow
Try logging your ___Promote varaibles when you try to promote, as well as what piece is
See what values aren't what you expect them to be
Well, i see that the type of piece is spawning. It is only black and spawns on a1 so it doesnt read position for some reason
It's getting that data from piece, so where are you passing in piece
Well, piece is a pawn that is destroyed upon promotion
which one
The one that reached promotion
Yea
How did you check?
Oh yeah. now it's gone. But now that I run it I see something else being weird here with the movement of these enemies. The entire cube has shifted towards the right where In reality they're literally placed right above the green floors and they have the exact same positions and scales so why is it moving like that?
Few different pawns went, all of them were destroyed on different tiles, then promotion spawning begun
Do they actually move or is it just that their starting position isn't where you expect it to be
Okay but how does that prove that the piece passed to this function is the right pawn
It works with 1st script, but for queen only
Also the waypoints have the same X and Y position
their starting position is fine.Its when theyre starting to move that they break up
heyyy
How are they moving
following the waypoints
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointFollower : MonoBehaviour
{
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializeField] float speed = 1f;
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
Then I would assume you should move the waypoints
The pawn is destroyed then i get to choose the button, they dissapear and a piece appears. It is black and on a1, so it doesnt reach position of a pawn
Hello
So since the color and position come from piece, you should log what that is so you know what it actually is
FUCK i got sidetracked and i didnt ask my question
anyways, visual studio doesnt work on linux so what should i use instead of visual studio code
I just ended a tutorial about this, i thought that team color indicates colot
Yea, happends a lot
Check if Rider works I guess.
Those are the big three.
Otherwise it's gonna have to be vim 😂
It probably does
