#💻┃code-beginner
1 messages · Page 394 of 1
no, you'll stop what you're doing and use !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hey quick question - how would I go about using loops like a for loop to iterate raycasts at varying angles. For example, this red line represents the ray cast. I would like to duplicate this every 15 degrees around the entire circle
I'd use Quaternion.AngleAxis to calculate a rotation
Quaternion.AngleAxis(angle, vector3.forward) * Vector3.right;
This will spin the right vector by angle
Ok
You can calculate angle based on your for loop's variable
I'll research that a bit
so is using this really that much better than learning on the go?
you currently have a very broken understanding of some really fundamental concepts
it is better to get a foundation from a single coherent source before you try to start learning things on the fly
I see, so for example, when i is equal to 4 then I can multiply i by 15 - I think I might have got it
"learning on the go" only works when you know enough already to extract more information from experience
you can't "learn on the go" from scratch
more general question, since unity has alot of built in features which arent c# exclusive, is it a good idea to use making games on unity as a means to progress into software engineering?
doing is a supplement to reading, not a replacement
You can also use Mathf.Remap to calculate an angle
wait, that doesn't exist lol
i'm thinking of the shader graph node
lol
damn, i got so excited 😔
too much knowledge
float progress = Mathf.InverseLerp(0, raycastCount, i);
float angle = Mathf.Lerp(0, 360, progress);
That's basically what a remap does
understanding c# will make you understand how to read/use properly any API including unity..
i see ok
yeah i get that, but i mean the plethera of unity exclusive things
like all the methods aand components you need to understand
unity exclusive things can only be used in unity
thats what the manual is for
but the concepts will take you much further
Which are called an API. Learning how to use an API will help in anything
yeah but i feel like the concepts are what take up much less time to learn
you haven't learnt either at this point
you need to learn both together
if you just learn the concepts, you can't apply that to actual code
ive learned a bit of c#
a bit is not enough
if you learn just the specifics for unity, you can never adapt and improve and apply that knowledge to other scenarios
you need both
(this is what computer science is)
learning c# without any big frameworks is the best service you will do to yourself, everything else will make way more sense
really? i havent encountered any c# issues that im aware of since i started this new project
just unity stuff
I can name 3 just by looking at your posts lol
haven't you been asking about c# stuff this entire time
The "unity things" you had issues with were actually c# issues
any question about scripting in unity is a question about coding, and unity uses c# for its textual scripting
Understanding c# would have made you able to resolve them
why is this my moment now working properly?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public Animator body;
private Rigidbody2D rb;
private SpriteRenderer sr;
public float speed;
void Start()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)){
rb.velocity = Vector2.right * speed;
sr.flipX = true;
body.SetBool("Walk",true);
}
if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)){
rb.velocity = -Vector2.right * speed;
sr.flipX = false;
body.SetBool("Walk",true);
}
if(rb.velocity == new Vector2(0,0)){
body.SetBool("Walk",false);
}
}
}
this is the code
could you tell me please cause then i can go to learn c#
This would be a c# understanding issue
if you know c#/programming, then you would know how to read documentation and extract the necessary info from them
your problems are not unity-specific
that one tbh i was focusing on the lines beneath since i thought the lines above were fine
you don't have the fundamental skills for programming, yet
go get them
if that makes sense
at least for copy and pasting code
the documentation talks about these
but that is not a c
thing is it?
c#
you've been told many times
It is a math thing
if you understand programming, you will know where to find the information needed.
yeah but i dont see the c# errors ive been told about yet
Basic logic that applies to all programming
direction vs vector?
errors ≠ issues
you lack fundamental understanding right now.
knowing c# wont magically teach you about vector3s but you will understand how to use in the code once you do..
you currently don't know what you don't know
alr if everyone thinks so ill do thaat
Yes, knowing vector mathematics is not unique to c# or unity or even programming
but should i do that before even movving to the unity learn course
But it IS very common in programming (especially game dev) of course
🥹 i got burried
me, starting with reading c++ source engine code without a lick of coding exp 
Explain your issue a bit better please. In words preferably
c# or unity learn first
creaate with code
okay thanks
C#
This is pinned in my clipboard haha
they should pin the w3schools one here its decent
i have attached a video below i wanted to show that the player suddenly stops moving forward when i go back and then go forward again then it works
replying to this cuz got burried
What collider shape are you using for the player?
box2d
Try not using a box, instead a capsule
that's probably not related to your code, are you using a composite collider for your tilemap
okk let me try
are you using tilemap ?
try also using a composite collider on it
oh dang my discord just updated lol 🦥
Hello again, im trying to iterate raycasts at intervals of 15 degrees around a circle, but this code doesn't seem to work,
oh great works fine now thanks
how do you paste small blocks of code in the code format
!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.
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector3(0, 0, i*15), distance, includedLayers);
Debug.DrawRay(transform.position, new Vector3(0, 0, i * 15) * distance, Color.red);
} ```
Thats it
cs goes on its on line
im trying to iterate raycasts at intervals of 15 degrees around a circle, but this code doesn't seem to work
oh ok
new Vector3(0, 0, i * 15) is just vectors pointing up at various heights
I was wondering about that, how do you translate that to rotation?
you aren't rotating anything there
well first off use Vector2 since you're doing 2d stuff
then you could rotate that or use trig
Ok, I'll look up some more stuff. Thanks
there's no method to rotate actually im just dumb
just use trig
cos = x, sin = y
thats what I was looking up lol
keep in mind they use radians
you could do
for (int i = 0; i < 360; i += degreeIncrement)
{
float angle = i * Mathf.Deg2Rad;
Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
Debug.DrawRay(transform.position, direction * radius, Color.green);
}```
I think
I think Ive used some method like rad2deg or something
that'd be the method
Ok, I think I understand that
Math time, thanks guys
also note that this starts at the right and goes counterclockwise (like polar coords)
if you need it to do something else then you have to apply an offset or a factor
Ok, any orientation should work
how does terrain pixel error work
if you get from 5 to 15, you won't rly notice the difference, but the triangle amount will go down ALOT
but as you increase it to like 25-30, terrain becomes less curvry but only far from player
and as you set it to 200, the entire terrain turns low-poly
Yes there is. Quaternion * Vector will rotate it
Could construct the quaternion with Quaternion.Euler then apply that to the current direction vector
i meant an actual c# method on Vector2
that was what i was thinking of
but yes quaternions are a thing im aware i just don't know how to use them lol
this is not what I suggested doing
this is creating a vector whose Z component is 15 * i
so it is a vector that points forward
they're rotations. you use them to rotate things
i know what they are. i know what they're used for. i don't know how specifically they're used, i haven't worked with them, so i wasn't comfortable recommending them
ah, fair enough
First three variables give a direction, fourth is the amount of twist around that direction
But generally you just DON'T use them directly
noooo im not ready
This is not correct.
Ah, that was how it was explained to me. I dunno I guess
consider this 90 degree rotation I made in Blender, followed by another 90 degree rotation (both around the Z axes)
to be fair, it's...a bit inscrutable
oh what the hell....
fortunately, quaternion math is completely irrelevant here
it should have just been called Rotation
So, x, y, z are colinear with the axis of rotation; w describes how much rotation around that axis in a non-linear fashion. The constraint here is that the total has to have a 4d length of 1, so as the amount of rotation changes, the length of x, y, z have to change inversely.
Yeah, I simplified what I was told incorrectly
And misremembered. This was from a while ago
For the love of god I don't know how to make a raycast from the gun's front to check what it hits. I asked chatgpt and he gave me this broken bs. Can someone tell me how this can be done?
Gun Code -> https://hatebin.com/ztagsogdlj
yeah, it's something close to what you described
When creating a scriptable object do you guys use enums?
the ray starts from this Y position. I have too many questions for this code, there's gotta be a simpler way to do this
just use firePoint.forward
enums aren't something specific to scriptable objects, nor is the inverse relationship specific to that. use enums where appropriate
line 44 is particularly bogus
Vector3 worldCenterPoint = transform.TransformPoint(centerPoint);
centerPoint is a world-space position, since it uses firePoint.position.y
yeah, that's the chatgpt code
so throw all of that hallucinated code out and just do...
Vector3 origin = firePoint.transform.position;
Vector3 dir = firePoint.forward;
what do we turn this to to make it work
Vector3 rayStartPost = gun.transform.position + gun.transform.forward * (gunLength/2);
if (!Physics.Raycast(rayStartPos, gun.transform.forward, out RaycastHit hit, maxRayDistance)) return;
hit.Succ();```
Make sure that your firePoint transform is rotated properly.
also I'm guessing I delete centerpoint?
I know that my question is when creating sciptctable objects do you guys use enums because I have seen multiple people on youtube say you must use them instead of normal variables
To make the Raycast out of the gun's front, you have to the take your gun's long side (the gun without the handle, not sure how it's called), and cast a Raycast from its tranform.position in its transform.forward direction, or whatever its axis is
It looks like this code is trying to figure out a "forward" direction without actually using the rotation of firePoint
by instead using worldFirePoint - worldCenterPoint
this is completely unnecessary
again, use enums where appropriate. there is no specific relationship between enums and scriptable objects.
again I'm asking is it typical to use them almost always for scriptable objects as that is what I've been told I'm not saying you can only use it there?
I'm guessing .forward since the gun is aimed in the Z direction from the start
but what about the rotation
jesus christ what part of "there is no specific relationship between enums and scriptable objects" do you not understand?
that is the answer to your question
No. It's not. They have already answered you that there is no reason for you to use enums specifically for ScriptableObjects. You use them in the same cases as when working with normal MonoBehaviours
rotate by gun rotation and we're good?
Then why did CodeMonkey and a few other tutorials say you should always use it what is that relation if its being said ?
Just junk?
if you have a firepoint, you can do this then
int maxRayDistance = 150; // 150 unity units
if (!Physics.Raycast(firePoint.transform.position, gun.transform.forward, out RaycastHit hit, maxRayDistance)) return;
Debug.Log(hit.collider.gameObject.name);```
link a timestamp where literally anyone is saying that
I will
I have no idea what other tutorials said. It's either that they're wrong or you've misunderstood them. I think the latter.
I dunno the subject, but codemonkey is... not good
I'll give it a go
I just need a raycast forwards of firepoint relative to the gun that logs the first thing it detects
https://www.youtube.com/watch?v=-PT-LADWymI&ab_channel=CodeMonkey he says it around 46 seconds
🔴 Learn why you should NOT use Strings https://www.youtube.com/watch?v=0_UiF-4-7xM
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
Quick Tips Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53vjCLV83wb7ZF2mYNLC_wQZ
Always use Enums for State handling inst...
he implies it is bad practice to use strings
i'm calling it now before i watch the video that the tutorial was actually telling you to use an enum because it was the most appropriate data type for the information you are trying to store as a variable and had literally nothing at all to do with the variable being on a scriptable object
notably, he's not writing a ScriptableObject here
if you use raycast, it will anyways return the first object ray met
he's demonstrating that you should use enums, not string constants
In his scriptable object video he only uses enums
There should be no reason to create a variable for the fire point, as you can simply cast the Raycast from the gun's position
then why did you link a completely unrelated video
it says cube
well, he wants some kind of firepoint
It's going to rain tomorrow. What color are my pants?
it was the video I was watching before to get an understanding of what enums were in the first place
which might be above or sideways from guns position
you aren't wearing any
because it's inside it, right?
close: shorts
are you conflating using enums instead of strings with using enums instead of any other type of variable? because enums are just a handy way to identify something using a compile time constant that isn't a string
so you aren't wearing pants, i got it right then
please show us the actual video, not another unrelated video that doesn't say what you said it did
don't forget that raycast won't return the collider which is bounding the start point
yeah, a 3D raycast will ignore those
how do we handle the case in which the gun is jammed inside an object? (For now I don't need to render it separately)
so if you start shooting from inside a cube, cube will be ignored
can we enforce this somehow?
Why would you?
isn't that only if the queries hit backfaces option in the physics setting is disabled?
if the ray hits something and it's distance is less than 0.2f it won't fire
cant you just get a list of raycasted objects and also check which objet the gun is colliding with
Hello, everyone
eliminating the ability to fire from inside or very close to walls
finding it
so is there a way to enforce the start collision?
what does this mean
Not sure what you mean?
to enforce the start collision
like, for the raycast to recognize the start collision instead of omitting it
u said the same thing twice
it is disabled by default
If I create an instance using a prefab, does that mean that two instances of this prefab will have the same identity as each other?
yeah
https://docs.unity3d.com/ScriptReference/Physics-queriesHitBackfaces.html
I believe this is for mesh colliders in particular?
Instances aren't references. So no.
I need to go test that carefully.
does it not do that by default? If your gun is inside the wall, you do a raycast from the gun to where youre looking at.
if the gun is inside an object, then the raycast will be the object the gun is in
Don't let the player get so close to the wall, or start the raycast from further back
sure, but that doesn't mean it cannot be turned on to get that behavior
btw @little forge what's the return for? Won't this cancel the update function?
so do you want the object inside the gun to be omitted?
or do you want the object inside the gun to stop the gun
it ignores the object the raycast starts inside of
if it doesnt hit anythign it returns
I'd like it to recognize that
I can't find the video anymore damn
!Physics.Raycast
It was a codemonkey tutorial I was following though but thats besides the point I guess if it doesn't make sense it doesn't make sense
And anthestiosity mentioned codeMonkey is bad why is that?
If brackeys is bad and code monkey is bad that's like 90% of the tutorials
ok so you
- do a RaycastAll https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html
- check if the gun is inside an object. if so, store the gameobject inside the gun
- loop through the raycastall result. if its the same as the gameobject inside the gun, skip it
he's not necessarily bad.. he writes in a really condensed complex way.. doesn't explain some basic things he assumes u would know..
When you have a class, which your prefab is, simply assigning another class to it will make them both have the same reference
yourObject = yourPrefab;
yourObject == yourPrefab; // true
When you simply instantiate a prefab, it will create its instance, and removing the instance won't do anything to the prefab
yourObject = Instantiate(yourPrefab);
yourObject == yourPrefab; // false
Destroy(yourObject);
// yourPrefab is fine
and plugs a utility library that he uses all the time
idk who anthestiosity ( <-- forgot bro's username mb ) is but codeMonkey is great from my experience
my only issue with code monkey's tutorials is that he relies too heavily on his own libraries and expects users to install them to follow along with his tutorials. of course i haven't had to watch any of his tutorials in several years so 🤷♂️
except from the library part, yeah
Code Monkey is bad for BEGINNERS imo
ah yes you are right he had me sign up for his email list to get the things I needed to
i hate when guides ask you to download their frameworks
fucking annoying
executing third party code on your pc while not knowing how they got started
He has OK code for intermediate and "advanced"
im making a tutorial series right now for C#, Raylib and Unity
no libraries other than in the base
So if I were to compare two instances out of the same prefab, would their == value be false?
whats your channel
not yet
cool.
ill publish the full thing
its a bucket list thing
right now im making like 2 projects simultaneously so im gonna perish
Learn.unity is always gonna be the best place to start, and codemonkey, brackeys, and others have clickbait channels that generally give bad practices to just get out content. Which is pushed by youtube itself of course
I don't understand what I'm supposed to do.
Surely, when Instantiating a prefab, it creates a new GameObject. These GameObjects are completely different and return false when compared
||Note that by GameObject I also mean the type of the instantiated prefab, as Instantiate is generic||
ok your first task is to learn how to use RaycastAll instead of Raycast
you're using raycast right now right?
Thankyou for your repllyy!!! 🙏 🙏 🙏 🙏
as a tutorial maker, i agree 🤣
RaycastAll returns all the objects that are hit by the line, not just one
very fun stuff
so take the first object in this array returned by RaycastAll
I hate unity learn but Im gonna give it another go because at this point I truly hate the youtube unity tutorials most of the time
unity learn doesnt do enough
I plan to teach unity basics then do guided projects
it does plenty to make u learn the processes
for art assets ill prob plug kenney all in one assets
yup
once u get the basics its up to you to research specific topics
I mean what do we define as basics though?
neat, let me know when you changed Raycast to RaycastAll
knowing how to read the docs.. write proper syntax, and be able to navigate the editor
okay so you think If I know that there is no point in untiy learn?
once you learn that.. no not really
but im not saying don't finish em
b/c its structured in a way to work ur way up
https://hatebin.com/thyvqoebcd
Still not detecting the entry collider. If I'm rushing just tell me
i never even did the learn route.. wish i had of
so how did you learn
Hard disagree
self taught.. and reverse engineering assets
- c#, if/else, while, for, switch, classes and OOP, interfaces, preferably worked on other coding projects
- know how to use the editor(right click to move around, right click + wasdeq to move)
- know how to create gameobjects
- know how to move around game objects in the scene
- the concept of parenting gameobjects in the scene
- what a transform is
- what a component is
- attaching components to a gameobject
- how to make your own components
- how to use SerializeField and link your components together
- abusing static variables and making singletons
i figured out how to do IK in about 30 minutes this morning
I know everything there besides static and singletones and interfaces
hot damn
once you know how to search the internet.. and u know how to write code.. and read errors ur golden
I got half of these down damn
singletons and interfaces are important
i find it hard to do stuff like state machines and behavioural trees
but everything else. is pretty simplified.. u dont have to write pretty code.. just code that works tbh
unless ur working in a team.. then write prettty code
Singletons are usually not recommended in non-game dev, at least not much, but they are very common and useful in games, especially in engines which consume Main
That's so cool
singletones?
damn I should learn then
you are in a good direction
class GameManager {
public static bool canMove;
public static GameManager instance;
void StartGame() {
instance = this
}
}
...
class PlayerController {
void Update() {
if(GameManager.canMove) ...
}
}
first variable in GameManager is canMove. you dont actually need to make a GameManager to use canMove. you can get it from the class name.
very fun stuff
how to create an ocean using code (with high vfx)
then if you do decide to make a GameManager you dont have to use serializefield
@eager spindle what's wrong here?
i looked at it
📸 typo recorded
looks correct
your object might not have a collider
or might not be the exact same collider
don't you need a reference to the class? Or you don't because its public
you mean the gun or the firePoint
Nooooo
Nicholas, I typeod. It is SINGLETONS lol
if you want really nice water rendering, you'd want to look at the high definition render pipeline
the gun has no collider so it doesn't break the player and all the other things
in this case no. you can use GameManager.canMove and GameManager.instance without a serializefield
HDRP water 🤤
because its public right?
they still need to be public but you dont need to getcomponent or serializefield
its because its public static
public static GameManager instance lets me use GameManager.instance without a serializefield
you are mixing some important concepts up here...
Singleton's Instance is a static reference to the class, so accessing the variables from it is pretty much like accessing the variables from a static class
YourSingleton.Instance.anyVariable
i know but i think you can use some math function to code it without touching to render pipeline
TheClass.instance.Function();
so we could say like if GameManager.canMove == true) {audioclip.PlayOneShot(walkingsound);
It lets you access the instance field from the class itself, rather than from an instance of the class
GameManager.instance.canMove == true;
It's true that this means you don't need to be given a reference to a GameManager
HUH?
No, you are missing the instance
== true 😭
You are accessing the type via a static VARIABLE
also just a general question, because this applies to web development, but will I get good at C# by just making different stuff every day?
it was a bool no?
Experience is good, yes
yes i learned a lot of unity and consequently game dev as a whole by doing dumb things
It is already a bool. No need to use == to convert it to a bool
you'll get better
`not necessarily
like making a skibidi toilet fan game
get well soon 🙏
This is not necessary. Simplify your code by changing
yourBool == true => yourBool
yourBool == false => !yourBool
Ah yeah ur right should be just what whatever and just use !thingy if false or thingy iuf its true
brain fart
what could be the issue outside the gun lacking a collider
how do we change better to good
is firepoint null? is firepoint.getcomponent<collider> null? could you store your collider in a variable rather than using getcomponent in the for loop
Constant learning
erm, it depends on your routine. and what ur chosing to learn.. when
i can't say.. its different for everyone
Anyone here who can help me with object pooling?
firepoint is a transform from inside the gun
when you work in the game industry you'll join a lot of companies with their own solutions for things, or you might even make your own solution yourself.
by solution it could mean making your own engine or unity extension
this is how people go from better to good
What do you mean by routine
because it challenges what you've learned and makes you google a lot of stuff
a lot more than just staying indie
I learned how to make unity extensions and unity GUI because Ineeded some stuff automated for my team
the steps you take each time you study/learn/work
What exactly is static is a method static or a class? What does that even do exactly?
hello would anyone be able to help me out with coding i am fairly new :3
how may we help
Ok so
I'm making a simple space game
Where 3 sizes of asteroid spawn
And when player shoot them
Larger one split into medium
While medium into small
And small one destroy
I'm destroying when using destroy(gameobject); but I heard game pooling is way better for massive spawn and despawn
So I'm wondering how I will able to achieve it
I can send my asteroid and asteroid manageer script (spawn asteroid randomly) here
think, make, fix with the help of others and the internet most of the time, learn from mistake, repeat
to simplify ofc
so like i wna make an silly fighter jet game yk
3d
where u can like fly fighter jets
fight others
yk
first step is to make a script that detects when the asteroid gets shot, do you have that right now?
please make coherent and full sentences
once that happens, when the asteroid gets shot, instantiate two more objects.
you mean you are Cloning Asteroids, object pooling will not help you here
apologies for interrupting you but when you write a programming question rather than sending multiple messages, write it like an email. you only get one message so include your whole message in it/
Maybe something with the actual code
Ye I'm sending 1-2 minutes
this line here "Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. " is like japanese to me
there are beginner c# courses pinned in this channel. start there if you do not understand how the language works
oh ok my bad.
Not cloning
It's like when a larger asteroid gets hit
It gets deleted and it spawn 2 more
You cannot use the new operator to create a static class, and these classes can only contain static variables.
You have to create normal classes to access their non-static methods or variables.
Nicholas nicholas = new();
nicholas.Eat();
While the static classes don't support that, and their methods are accessed directly, without the reference.
NicholasUtility.CreateNew();
Any can be. Method, class, and variable can all be static
Would you be able to help me out regarding my idea.
I do know how Asteroids works and I'm telling you object pooling is not necessary here
this sorta makes sense
My brother knows C & JAva would he be able help me or is c# to different
static in class and static in members is slightly different;
a static class can only hold static members, that's all it does
static on members actually has an affect
a static member is accessed through the class directly rather than through an instance
i still need help with this
Yeah, I know. You can also have static methods in non-static classes, which also don't require the instance of the class and can be accessed directly
Yep I don't know what half of those do back to the basics it is then
c# is c-family, they have similar fundamental syntax, but c# is significantly different in paradigm and structure from c
it's quite similar to java though, java just doesn't have static classes (which doesn't detract any functionality, you just can't enforce not having non-static members. you can restrict construction though)
did you try reading the descriptions
yes
Yes probably but it's a part of my project
I suppose, Java is pretty the same
importantly: using static when declaring a type doesn't add any functionality -- it's strictly there to prevent you from adding any non-static members
why do you need to enforce class to be static tho
doing it without static
public class GameManager {
public bool canMove;
}
public class Enemy {
[SerializeField] GameManager manager; // drag gamemanager here!
public void Start() {
if(manager.canMove) ...
}
}
doing it with static
public class GameManager {
public static GameManager instance;
void Start() {
GameManager.instance = this;
}
}
public class Player {
void Start() {
if(GameManager.instance.canMove) ...
}
}
static variables explanation. GameManager has a static variable called instance, which keeps track of the one and only GameManager. the static variable instance is not depending on anything, so you dont need to create a GameManager to access instance.
lets say you have 100 players in the game. its not good practice to drag Gamemanager into every player if it were a serializefield, so you can use a static variable
I'm going to seems like a there is a collective opinion that I should really get much more understand of c# as a whole then move to unity
apologies for big block
suree, do DM me and I can guide you through the process
You need to have a decent handle on programming, yes.
If you don't know any of the words you're going to have a miserable time of it
that's what Unity Learn is there for
that explains a lot.
Not quire sure what you mean
yep. if you want to have a good handle on c# you want to make a few practice projects. you could try making your own engine in Raylib for c#
he means you can't add non-static methods or variables into a static class ig
which will get you a lot of practice
i would recommend against dm help especially when the support server exists
@eager spindle ```cs
using UnityEngine;
public class Asteroid : MonoBehaviour
{
public float minSpeed = 1f;
public float maxSpeed = 3f;
public GameObject mediumAsteroidPrefab;
public GameObject smallAsteroidPrefab;
private Rigidbody2D rb;
private ScoreManager scoreManager;
void Start()
{
rb = GetComponent<Rigidbody2D>();
float speed = Random.Range(minSpeed, maxSpeed);
float angle = Random.Range(0f, 360f);
Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
rb.velocity = direction * speed;
scoreManager = GameObject.FindObjectOfType<ScoreManager>();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
if (gameObject.CompareTag("LargeAsteroid"))
{
SplitAsteroid(mediumAsteroidPrefab);
}
else if (gameObject.CompareTag("MediumAsteroid"))
{
SplitAsteroid(smallAsteroidPrefab);
}
Destroy(collision.gameObject); // Destroy the bullet
Destroy(gameObject); // Destroy the current asteroid
}
else if (collision.gameObject.CompareTag("SmallAsteroid")) // Check if collided with a SmallAsteroid
{
// Update the score using the ScoreManager only when a SmallAsteroid is destroyed
scoreManager.UpdateScore(10); // Add 10 points for destroying a SmallAsteroid
Destroy(gameObject);
}
}
void SplitAsteroid(GameObject smallerAsteroidPrefab)
{
for (int i = 0; i < 2; i++)
{
GameObject newAsteroid = Instantiate(smallerAsteroidPrefab, transform.position, transform.rotation);
Rigidbody2D asteroidRb = newAsteroid.GetComponent<Rigidbody2D>();
asteroidRb.velocity = Random.insideUnitCircle * Random.Range(minSpeed, maxSpeed);
}
}
}
codepaste my man
yep thanks for your help
When you add static to a member, you're fundamentally changing how you can access the member. It lets you access the member from the type itself, instead of from an instance.
When you add static to a type, you're not adding any new capabilities to it. You're just saying "no instances may be created".
this is more for a guided project than a problem everyone encounters
static class X {}
class X {}
```are functionally equivalent. the `static` only comes into play when non-static members are added
bingo
Huh
!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.
do you want to have the responsibility of guiding them 24/7 then?
I would recommend not asking someone whether you can dm them, but there's nothing wrong in that person suggesting to help others themselves.
this server is open 24/7, im sure you aren't
yes actually ive taken a few "apprentices"
i got this
I'm off to practice c# thank you everybody for the help it seems all my issues stem from my lack of understanding from the fundamentals I'll be back with more questions once I get those out of the way so my questions are more unity specific rather than coding
aight, your responsibility then
ive seen it gone poorly a few too many times to just let it slide
Got it. I see what you mean now
wat this
Check out the c# server btw for specifically c# questions
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Read it
its how to make funny code blocks
like this
Especially the large code blocks section
That is what they did originally
here's a backtick to get started `
They need to use the large codeblocks part
not to be confused with the apostrophe '
something you are supposed to read and act on
using UnityEngine;
public class Asteroid : MonoBehaviour
{
public float minSpeed = 1f;
public float maxSpeed = 3f;
public GameObject mediumAsteroidPrefab;
public GameObject smallAsteroidPrefab;
private Rigidbody2D rb;
private ScoreManager scoreManager;
void Start()
{
rb = GetComponent<Rigidbody2D>();
float speed = Random.Range(minSpeed, maxSpeed);
float angle = Random.Range(0f, 360f);
Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
rb.velocity = direction * speed;
scoreManager = GameObject.FindObjectOfType<ScoreManager>();
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
if (gameObject.CompareTag("LargeAsteroid"))
{
SplitAsteroid(mediumAsteroidPrefab);
}
else if (gameObject.CompareTag("MediumAsteroid"))
{
SplitAsteroid(smallAsteroidPrefab);
}
Destroy(collision.gameObject); // Destroy the bullet
Destroy(gameObject); // Destroy the current asteroid
}
else if (collision.gameObject.CompareTag("SmallAsteroid")) // Check if collided with a SmallAsteroid
{
// Update the score using the ScoreManager only when a SmallAsteroid is destroyed
scoreManager.UpdateScore(10); // Add 10 points for destroying a SmallAsteroid
Destroy(gameObject);
}
}
void SplitAsteroid(GameObject smallerAsteroidPrefab)
{
for (int i = 0; i < 2; i++)
{
GameObject newAsteroid = Instantiate(smallerAsteroidPrefab, transform.position, transform.rotation);
Rigidbody2D asteroidRb = newAsteroid.GetComponent<Rigidbody2D>();
asteroidRb.velocity = Random.insideUnitCircle * Random.Range(minSpeed, maxSpeed);
}
}
}```
Do not do cod- op. NO, use a paste site
That's too big. You should use a site
https://gdl.space/
please do not
site is sus
no
No, absolutely do not do .txt
It is the rules of the server
what server recommends files
Mobile need to download it for one
only to 100 lines
For everyone to download it on their device?
No, actually I tested this up to about 2k lines
But it still requires download on mobile.
There is a reason paste sites are the rule
make a screenshot of the code 
But it's still hard to read
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Now that's even worse
how? i only ever see up to 100 lines on desktop when expanding the file
Also no, stop posting shit advice
Stop suggesting things against the rules
personally im not fond of paste sites especially now when you can fake links
There are two buttons to expand
How much troubles does it cause you on avarage?
📃 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.
oh yeah the expand thing, i was remembering the preview
I have never seen that happen once personally
i know how to spot when the fake links are being posted but some people I know irl dont and lost their game accounts to phishing sites
very dumb that people are falling to those in 2024
can you help me? lol
phishing still requires that you log in to whatever link you were sent
if they fell for phishing with a fake link, they wouldve with the real one
Why do you refuse to just share the code properly?
can you put literally any effort into getting help and just read this: #💻┃code-beginner message
@eager spindle Stop derailing the conversation.
what's wrong with the current code?
is the asteroid not splitting
Are these the kind of sites which get all your device's info only when opening them?
isn't that all sites (user-agent http header)
They want to make object pooling
https://gdl.space/aronozejum.cpp ?? like this 😿
You succeeded! ||I have not stopped believing in you once||
Yes 🎉
everything is working fine , just instead of delete i need to apply object pooling
Ok, I don't see any object pooling happening.
What did you try so far?
Have you looked into the ObjectPool type that unity provides?
idk how to do it with 3 objects
for object pooling you'll need an array of gameObjects first.
GameObject[] largeAsteroidPool = new GameObject[10]
under start, set all elements of the largeAsteroidPool to a new large asteroid. set this asteroid to be inactive.
when you need an asteroid, set the asteroid to be active and set the position of the asteroid. when you dont need the asteroid, set it to be inactive.
if you insist on doing this you will need 3 pools
i mean i know problem i face is when , 2 medium asteroid spawn from large asteroid destruction
wouldn't it be 3
to do this for the small and medium asteroid pool make 2 other arrays
https://gdl.space/favokoninu.cs i hab 3 arrays
look
but dont add or remove from this list
or itll defeat the purpose of an object pool
why not use unity's built in object pooling class?
seems pretty reasonable to add to it if you don't have enough objects...
tbf object pooling is an important thing to learn
they hab?
I think this is a school project
yea just dont do it every frame
and choose a good starting number so it doesnt change too often
did you do no research?
personally I havent used it before, unity's object pooling system
you've been told this quite a few times....
i can't imagine that someone who is pretty much incapable of reading instructions is going to be able to follow along with your instructions for creating an object pool
yeah this is kinda why i don't like people opening up their dms... community support is good because there's an entire community, able to give multiple perspectives and opinions and suggestions...
i m on version 2021.3.29
going into a community support server to find a personal tutor just nullifies the benefit of asking in a community to begin with
i have these 3 scripsts to change to succesfully apply object pooling i will share
then why are you even in this conversation?
teaching the user the basics of object pooling rather than just directing them straight to the library
basics ≠ internals
but you said yourself you've never used it so how much do you expect to teach?
im talking about making a normal object pool rather than using unity's internal object pool
teaching to implement isn't the same as teaching to utilize
sure but if the first thing you try to change is making them use an array instead of a list, well that's not a very good or even relevant change so is your teaching really going to be worth it to that user?
up to them
i havent had the need to expand my object pool before
just choose a good fixed number at the start
if you want to make a proper object pool, you'd be using a queue not an array anyway 🤷♂️
i have these 3 scripsts to change to succesfully apply object pooling i will share
https://gdl.space/efociwubek.cpp (Asteroid script control asteroid spliting and destroying on impact with bullet)
https://gdl.space/uyeqexaton.cs (object pooling)
https://gdl.space/awamojofix.cpp (Asteroid manager which spawn random asteroid at random location)
I see some beginners asking "how do I make game" rather than "how do I do ...", they dont ask precise enough questions and they're just ignored by the community because they don't know how to break their game down, and even when I do help them in chat people from the sides constantly bombard them with shittalking because they're doing something wrong
not very fun for them
How would I make it to where multiple scripts can reference the same instance of a script across scenes? I have a settings menu in the main scene of my game, each slider and toggle has its own script that handles its functionality. Currently I am trying to make a main menu, and my idea for applying the settings across scenes is to use a script which holds the values of each of the settings. I am unsure of how to make a single instance of the script accessible across different scripts.
across scenes? when you go across scenes the GameObject is destroyed
DontDestroyOnLoad
😦😔
I am not using a gameObject, I am using a base C# script that sits in unity's assets.
for example
Wouldn't a Stack be better for an object pooler?
how is this object created?
i personally use a static class to store the settings for my game and load using the RuntimeInitializeOnLoadMethod attribute and save when settings have been changed
Technically, yes
queue and stack are completely interchangeable for an object pool, queue just lets you get the oldest object in the collection first whereas stack gets the newest
asking good questions is a skill that needs to be developed alongside everything else. there's gotta be a place to practice that
So, how would other classes be able to access a single instance of this static class?
there is no "instance" because the class is static
a static class can only contain static members
Have you still not learnt C# basics, via the Class name
"single instance" is a singleton, not a static class
public static class Settings {
public static int volume;
}
...
Settings.volume
this is a static class
I understand now, sorry.
anyone?
You didnt actually ask a question in that block.
this does look like object pooling so what do you want changed
idk what changes to commit in asteroid and manager script
changes to achieve what
I know a decent amount of C# using monobehaviours and scriptableobjects; however, this is my first time using custom static classes.
Take a minute, and actually think what you're asking. You showed code and said "what do I change?". No one knows what your game or issues are
You'll get much better responses if you actually can ask something.
Sorry but this is basic MS Learn C# 'Hello World'
the ms docs use a lot of terms unfamiliar to new programmers, while it is correct it doesnt teach beginners
how do you reference a MonoBehaviour to extend it, or a Collider to get a collision, or a RigidBody to get a component
I understand the docs now but not 4 years ago when I started unity and programming
by name
why istead of using the pool its creating new objects?
you told it to
in SpawnAsteroid, you're calling Instantiate, that creates a new object
it calls SplitAsteroid which instantiates an object rather than getobject from the pool
Previously, I was unaware of what the static modifier did, I understand now. I have understood since uldynia provided an example.
it.. doesn't actually affect accessing the class
static on a class doesn't really change anything
what should i do instead?
it forces people to make variables static
get an object from the pool
look at the function you created in the objectpooling script how do you get an object from the pool
when developing. it doesn't change how you use the class at all
yea it only affects your teams who want to inherit the class
It usually takes more time to create beginner-friendly explanations
im willing to do that
Im like very new to this . can you explain how?
public static class Settings {
public static int volume
}
public class Settings {
public static int volume
}
are the exact same thing. however,
public static class Settings {
public int volume
}
is invalid because you try to put a variable that's not static, into a class that is static
You have the static accessor and the method. So Type.Accessor.Method
I don't remember the names
most of my work is indie so i dont bother making static classes, only static variables
but if you want to force someone to only use static variables then go ahead use static class
Well they serve very different purposes. Not sure how being indie affects the choice
so in future if someone wants to
public static class MoreSettings : Settings {
}
they must keep everything static
no one inherits my code so I don't have to think too much about public/private accessors 
wrong person
What I also not like about many tutorials is providing 200-line code blocks for the methods, which can easily be explained in much less lines, and, perhaps, several examples. You then have to find the explained method in this huge snippet and check out all the methods related to it. So, please, make sure to note that when doing yours!
access the pool, find one that's inactive, put it in the right place, and enable it
No one does to me either... but that doesn't mean I don't care about proper code structure
yep I make guided projects rather than just paste a block of text and expect them to know everything, or make then download a library and show then 1% of the code in the repo
Alright, just to confirm. If I were to say: Settings.leftHanded = true; in a script. Then I did Debug.Log(Settings.leftHanded) from a different script, it would log "true" in the console?
yep
Bet
It depends.
public bool leftHanded
{
get => _leftHanded;
set => _leftHanded = !value;
}
||Naming violation||
rare case but yes that's true
Also, if the script is static, do I need to initialize the script at runtime. And if so, how could I do this? This is what I have currently ```cs
public static class Settings
{
public static bool fullscreen = false;
public static bool leftHanded = false;
public static bool highContrast = false;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
public static void RuntimeInitializeBeforeLoad()
{
}
}```
nope you dont
Why would you do this?
anything that's static is loaded when the class is loaded
thats the first time ive seen that macro
your Settings doesn't interact with unity at all
it doesn't need unity to tell it to load
Thank you.
[RuntimeInitializeOnLoadMethod] is very useful if you want your static to have methods that immediately run, like Awake or Start does. I use it often, when I need that
couldn't you just use a static block
But to be safe I use the option for 'after scene load'
A static block?
Oh that's perfect! I could use this to load settings from a file.
how do i fix this?
{
ReloadAR();
}
}
public void ReloadAR(float ReloadAmmount)
{
ReloadAmmount = ARMagSize -= ARAmmo;
}```
oh wait c# uses a different form of these, it's a static constructor instead
If you need your initializing method to access anything in the scene, use this to be safe [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
class X {
static X() {
// run on class load
}
}
you need to put something in ReloadAR()
a float
in the ()?
oohhh
do you not see the difference between
ReloadAR();
and
ReloadAR(float ReloadAmmount)
?
you probably don't want ReloadAR to have that parameter
it isn't doing anything useful
you're just reassigning it
wdym?
You can, but the runtimeinitializeonload attribute has extra options for specifying when you want the method to run. Like the option I mentioned above will ensure it doesn't run until after the scene loads, so that your static method can access stuff in the scene without issues
your method ReloadAR takes a parameter, then it immediately throws away that parameter
it isn't doing anything
is there any reason why the post processing changes by script is not showned?
here is the script, it is fairly short
public class PlayerGForce : MonoBehaviour
{
Entity.EntityFastMovers Entity;
[SerializeField] Camera cam;
[SerializeField] Volume volume;
Vignette vig;
void Start()
{
Entity = GetComponent<Entity.EntityFastMovers>();
volume.profile.TryGet<Vignette>(out Vignette vignette);
vig = vignette;
}
private void FixedUpdate()
{
vig.intensity = new ClampedFloatParameter(Entity.GetVelocity() / Entity.MovementData.maxSpeed, 0.2f, 1);
}
}
because you are not changing any values on the settings in the profile. you output your vignette settings to a local variable then immediately assign a different object to that local variable
actually that last bit was wrong, you are assigning the local variable to the field
i misread the code
what should I change then?
I thought vig is already a reference to the volume profile vignette component
have you confirmed that the values you are using are what you expect them to be?
yes, you can see in the video that the value changes
not reliable advice but do it the dumb way and use TryGet every frame. last time I worked with volumes this is what examples online did.
vig could be a copy of vignette
I will try, thanks!
if it were a copy it would need to be assigned back (it doesn't)
its so much easier just to make another profile with the settings you want and just blend between the 2 Volumes with separate profiles using the weight slider
sadly does not work
what about enabling override for vignette before starting?
how so?
changes nothing
huh alr, I will do that
yea I think this is the better solution. the new volume that overrides the global volume should not override anything besides vignette
things will get tricky if you're gonna use multiple volumes (> 2)
just make sure the one you want to fade in has higher priority
you probably need to pass true to the ClampedFloatParameter constructor for the overrideState parameter which defaults to false
I have done that, not the case
hey remember when you asked that question in #archived-code-general and were provided an answer?
oof
My bad I didn't see it
copied these from my old code for an aiming system but how do i replicate this code with what i have new
okay well i recommend going through the basics of c# if you still don't understand what you did wrong. there are beginner courses pinned in this channel
@rich adder blending works! thanks a ton, and everyone else too
nice!
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
📃 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.
ok
is the effect sexy!!!!!!???
With the beginner course you mean "intro to c#"?
that is one of the beginner courses that i was referring to, yes
interesting use of vignette
i will check that out thank you
ahahaha drunk driving sim!
lol yea but now you can ragdoll on crash and not get hurt
dear god
all til that adrenaline runs out!
the flashbang though
sorry. I'll take it down not to blind anyone else
(someone should totally make a game about fighting people but if you stop fighting, your adrenaline drains and you pass out)
#archived-shaders probably
i believe they made a movie called Crank like that lol
my bad, thanks
gotta search that up rn ahaha!
a little bit more rated R though 😉
basically if his heart stop he die so he needs constant adrenaline rushes
omg, it existed
anyways, if we are going to talk, go to a different channel!
let the others have their coding help
if(Gun.transform.rotation < -90 || Gun.transform.rotation > 90)
back to unity code
use a code block my guy
i found out the problem how can i do this but working
rotation is not a single number
but for short ones,
do this
do look into how transforms work
how
rotations are stored as quaternion @long jacinth
(your stuff goes here)
thanks
gucci
hmm how do i convert it
so basically
rotation on the editor xyz are essentially Vector3
but for reasons, they use Quarternion
to use the Vector3 version, do
Quarternion.Euler(vector3)
which part of the rotation do you want?
transform has a few things you can use.
transform.position, a Vector3 which is the object's position
transform.eulerAngles, a Vector3 which is the object's rotation in degrees. look into quaternions for the better way to store rotations.
transform.scale, a Vector3 for how big the object is.
fun resources to read:
https://docs.unity3d.com/ScriptReference/Transform.html
https://www.youtube.com/watch?v=zjMuIxRvygQ
oh nvm then
anyways it is like
||if(Gun.transform.rotation.eulerAngles.(youraxis) < -90 || || Gun.transform.rotation.eulerAngles.(youraxis) > 90)||
to fight certain spoon feeding allegation
if you have any questions about transform let us know.
the purpose of transform is to describe where an object is, how it's rotated and how big it is.
ayo, how does on one properly create a network behavior script? you just create a mono behavior and change those words to network behavior?
yes
those words meaning something
its called a parent class
maybe you should not be starting with networking..
ya thank you
yo guys thanks ima watch that video about quaternions
funni math stuff
in most cases on unity you can get away with using eulerangles, but if you do go ahead with your own engine youll learn to love quaternions
im struggling to create my 2D engine over here 😔
you dont really need to know how quaternions work
salutations
just know what they're for thats it
we love opengl
ok thank you
all fun until opengl batching limit
and their dumb web gpu usage
not to spoonfeed too much but you can look into transform.Rotate
quaternions are hard how
as long as you understand, what you see inside the inspector is the rotation in euler Angles which is usually what you want to work with.. but the rotation should ideally always be kept quaternion
so any method you would do rotation = Quaternion.Euler
etc
ok thanks guys
(if you have intergrated graphic card on your cpu) they will use that and not touch your 4070 or whatever else you have)
Yikes, good luck (understanding) . . .
you need to enable hardware accel in your browser
i think edge has it off by default
bruh like pie is just a random number its not that different than regular math
it doesn't work I tried
major yabai
I made a unity webgl project for one of my assignments and had to guide my lecturer on how to enable webgl after complaints that it was laggy
it ran at the full refresh rate afterwards
huh
terrible idea, but it worked
Can someone help me with this error? im trying to load up the 2d platform microgame
please don't crosspost
sign into unity?
if you absolutely decimate your texture before using the fragment shader! everything runs kinda smooothh
idk
then again yall always tend to use cinemachine rather than figure out the camera controllers for yourselves..
the wonders of webgl, its purpose was to give computers access to your gpu to make beautiful graphics
yet you ground all your shaders to the old world 
I am signed in
what happens if you click revert factory settings
not THAT bad
You are already discussing it in #💻┃unity-talk
yea sorry i hadnt gotten a response and i thought it wouldnt work in that i felt this mightve been a better spot
@frank delta There's no off-topic here. Read #📖┃code-of-conduct
when multiple developers are working on a scene's UI, is it protocol to make multiple canvases? or multiple prefabs within the canvas
this is more of a survey than a help
I've been using multiple canvases until recently when one of my canvases wasn't displaying so I'm wondering how companies do it
...at the same time?
yea, one member work on dialogue the other work on objective system
if at the same time, splitting them out def works better
oh well HUD vs dialogue would probably be different canvases to begin with i feel
saved us from having github conflict every hour
how would one split it out though, multiple canvases or multiple prefabs within a canvas?
or at least distinct siblings
i wanna know how others do it
probably a question for #archived-game-design?
since our project arent gigantic, we just make different test scenes for everyone involved
i dont understand how a project can have hundreds of developers
#archived-game-design shall we?
100 people are definitely not 100 times more productive than 1 person
you get diminishing returns
oh right, this moved lol
👻
I'd use separate canvases to limit draw calls and for each system and decouple any reference to one canvas. Makes it easier to hide/enable UI for customization . . .
using seperate canvases has optimisation benefits? 
Yea, very much so . . .
Any GameObject or UI that updates will redraw the entire canvas . . .
my ass with a MainMenu made out of one colossal canvas:
(I only have a small part of the menu activated at any given time)
so it's ok
If you have lots of UI that's all active at once, and you can chunk it up into separate canvases, you should definitely do that
thats a major problem for me because for my current project I tried to put everything in one canvas and I have an inventory
If you have one UI element that constantly updates, say a health graphic or value, with 30 other stationary UI elements; all of them will redraw every time the health graphic or value changes . . .
In general, I'd use a separate canvas for an inventory . . .
Can I have multiple SOs in the same file?
No, you can't define multiple MonoBehaviour or ScriptableObject classes in one file.
Also, if I do need to separate all ym SOs in multiple files, anyone know a Visual Studio shortcut haha
Unity doesn't care about the name of your class -- it cares about the file it came from
Oh ok
use ctrl + . extract them into a new file
Nice, thanks!
What's a simple way to make the NPC face the player when they are speaking to them?
Use a separate file for all your classes or types. Takes the guessing out of where they are . . .
dot product check which side you're on
I can finaly create events through Unity's Editor 🥺
How come my card data has no attributes in the inspector?
This is the code for CardData.cs
It was showing before I put {get; private set;}
REally, before I refactored the gigs out of my code lol
Bruh, !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.
get; private set; are for properties. These are variables with the [SerializeField] attribute . . .
Properties do not display in the inspector unless you use an attribute . . .
You're trying to combine both . . .
Yup I need it for my game logic
- to create Prefabs easy to modify
- to add my game logic to it and integrate it to my architecture
Huh, you need which one? You have variables but are trying to use them like properties . . .
Apparently, autoproperties does not work with Scriptable Objects
So, basically, what I understood
Scriptabble Objects Attributes can't be changed at run time
Is that correct?
So I should just use them as constants
Stuff like this:
inputVector.y == 1 ? playerRigidBody.AddForce(0f, 10f, 0f) : playerRigidBody.AddForce(0f, 0f, 0f);
doesn't work because i check an vector value?
Or because I try to call a function in the consequence?
Ok, I think I get it now.
Have u read the docs on ternary? https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
evaluates a Boolean expression and returns the result of one of the two expressions,
Glossed over it... but didn't get it
Ah I see your explanation does wonders 🙂
Kinda thought its just a "shorter" if statement, but its actually allways giving a return right?
The core problem is that, if you write an expression as a statement (basically, as a line of code), it must be one of:
assignment, call, increment, decrement, await, and new object expressions
The conditional operator is none of these.
I'm not sure of the exact justification for that rule.
In Java, for example, I'm pretty sure you can freely write stuff like:
3;
C# does not permit this
I suppose the point is that, in most situations, there's no point to writing an expression like that, so it must have been a mistake by the programmer
No explanation here was mine. I copy and pasted exactly from the docs
Yes it always returns the value
was afk. you can display auto properties in the inspector; you need to use the correct attribute . . .
this has nothing to do with being a scriptable object, mind you
it's entirely about how Unity serialization works -- which is the same for any unity object
you can change/mutate an SOs value, but you should not because any other object (class) with a reference to it, will have (point to) those changes . . .
properties, variables (fields), and methods are the same for all types. it's not specific to SOs or any particular class . . .
Yeah Visual Studio prompted me with the same thing.. but isn't addforce() a call?
What I wanted to do was use my scriptable object instancees like any other class
What you've written is, in the eyes of the compiler, no different from:
true ? 1 : 2;
which is why i made everything with auto properties, to consider SOLID, basically
(although, AddForce returns void, so there's no real way to write an identical expression without function calls)
I don't want to alter my SO objects outside of runtime, what I want to do is instantiate copies of them in code and modify those instead
Yeah I see.
[field: SerializeField] is the attribute to display properties in the inspector. also, properties should be PascalCase, and your GetHealth method is unnecessary because that's what your Health property should already do. it's read-only . . .
Oh GetHealth exists for IDamageable interface
Otherwise I would've tossed it
that defeats the purpose of an SO. just create a regular C# class: POCO, and declare a variable of that class in your SO. then you can copy that C# class and mutate its values without affecting the original SO . . .
Wouldn't it be easier if SO let me do that tho
I wouldn't have to create another class
it doesn't defeat the purpose
the scriptable object contains the data
You can create instances of SO but you should dive a little deeper into the problems with doing so before actually doing it
Ok xD
basically, the SO_CardData SO is a wrapper for CardData C# class . . .
So apparently SOs hates interfaces 🙂
this is probably the "right", performance efficient way
But i'm just gonna go with my way because it's one less class babbyyy
Creating a new C# script has started becoming my most hated activity lately 🙂
can unity serialise a list of a list?
is it not convention to make public variables capitalised
🤔 it takes 5-10 secs . . .
Exactly 🙂
5-10 secs to add a potential bomb to my code database 😄
jokes aside
I'll just choose the minimum amount of classes to keep the code more maintainable
being a solo dev has been literally hell 🙂
By that logic, have your entire game in 1 class. Need to fix anything, its only a change to 1 file!
Thing is, why add one more class when I could just use my SO class to hold the same data and have the same behaviour haha
It makes no sense
Line 3 is c# convention, although not sure if unity differs. Could either be some unity specific thing or the quiz might just be wrong
public struct ReplayPlayer
{
public CharacterEnum character;
public int characterColor;
public int characterID;
public List<List<ButtonState>> _buttonRecording;
public List<List<MoveState>> moveRecords;
[NonSerialized] public PlayerInputController inputController;
public bool isReplay;
}
is there a way to make the nonserialized thing show up in the inspector? i have it as [nonserialized] so the json convert doesnt try to serialise it, but i need to be able to see it in the inspector
Then you should look the downsides of SO, especially if you're creating instances at runtime. I said the same above somewhere, it's not as simple.
nvm i found a fix
Do you have any resources so I can look into this?
I'm literally creating SOs all the time in my game lmao
I designed it so that each action is an SO
Can you still see it in debug mode? Usually I would create classes specific to what I wanna save so I dont have this issue
Not aware of any that goes too deep into it, but theres a difference of creating an asset in editor time and creating an instance at runtime. The most commonly brought up issue is that changes dont persist to these, and may reset back to it's original state if it's not referenced anymore in a scene. If you're creating instances, you also need to manually destroy them. It's not hard, just a pain compared to using plain c# classes, because the GC handles this for u
Oh, I see
This seems pretty important info
How do I destroy a SO instance?
i just replaced [nonserializable] with [jsonignore] which achieves the same thing for me
the same way you destroy any unity object
*eye Twitch ok im stumped here. Iv got a Sav Data script and It MAKES the files, so hurray for that, and the Inventory Section works perfectly fine, but The Player World Location part does not. Im TRYing to make it so while the update loops run Player POS updates in realtime. Player Object POS does, and I'm trying to feed that data into the other variable, but it doesnt work. I cannot figure out why, is there something really stupid about [System.Serializable] ??? When i press load all the Vector3 variable stay at 0 so saving player pos is getting hard
I have this on all my zombies, its my function for them attacking, This if statement seems to always go through. player is the player gameobject, that the zombies target, why does this if statement go through if the prints are equal
I have NO idea what im doing wrong, this is my first time actually trying to play with JSON and i just dont get it
i agree, a public variable should be capitalized to signify its intended use when looking at a class' members using dot notation . . .
private void FixedUpdate()
{
if (!started) {return;}
foreach (ReplayPlayer rep in _replay._replayPlayers)
{
rep._buttonRecording.Add(rep.inputController.buttonList);
rep.moveRecords.Add(rep.inputController.moveList);
print("Added " + PrintList(rep.inputController.buttonList) + "to buttonlist");
print("Added " + PrintList(rep.inputController.moveList) + "to movelist");
rep.frameLength++;
rep.lastMove = rep.inputController.moveList;
rep.lastButton = rep.inputController.buttonList;
}
}
I'm getting proper console logs, but when I actually go to check the Json, it doesnt actually add them to the list. why is this?
Well, I don't see you doing anything with a json in this code.
You'll need to provide more details. What the heck is ReplayPlayer, _replay and _replay._replayPlayers? And why are you accessing fields that should be private according to their naming convention?
Yeah my naming conventions are abysmal honestly. I've just decided to call it a night for now so I'll ask this question again tomorrow cus I don't have the project open anymore
It will probably come to me as I sleep
should i make everything inside an object null before Destroy()ing it?
No
I saw in a video that Unity doesn't necessarily deallocate memory after Destroy() though
And that references to it should be null
However, my thinking is that if I destroy() an object all of its properties/fields will be destroyed as well, correct?
Hey guys, so I have been trying to detect a side switch (meaning detecting if the player has went from left to right and vice versa) by comparing the current position and the previous position . the problem that I am having here is that the if statement that checks if the player has side switched always returns false and thus it never executes the side switch. Here is an example of my code:
void Update(){
CurrentHorizontalPos = transform.position.x;
PreviousHorizontalPos = CurrentHorizontalPos;
Debug.Log(hasSwitchedSides); //Always returns false and not true in all cases
}
private void EnabledSideSwitch(){
if(PreviousHorizontalPos != CurrentHorizontalPos) hasSwitchedSides = true;
else hasSwitchedSides = false;
}
What could be the issue here?
when a unity object is destroyed, any (of its) components on that object will be destroyed along with it . . .
Properties and fields don't exist outside of objects in c#
(Object being distinct from GameObject)
So yes, if you destroy the object, all of its member fields and properties will be destroyed as well
technically they wouldn't be destroyed at all since c# does not really have the concept of destroy. Once nothing else references that object and it gets GC'd then anything only referenced by that object will also get GC'd
So I don't need to set them to null before destroying the object, right?
it's a bit complicated. when you call Destroy, the object is marked for destruction, but that doesn't happen until the end of the frame
other references to that object will not set to null, so checking for null will return false because the reference is not null (even though the object is destroyed). what you should do is assign the object to null after calling Destroy on it . . .
Oh ok
Thanks for the explanation!
Are you people really thorough when it comes to memory handling?
Not unless it's an issue. At which point you'll use the memory profiler to optimize it correctly.
Most of your memory consumption is gonna be from texture and mesh data anyway
public class Board : MonoBehaviour, IDestroyable
{
public static Board Instance;
public List<LinkedList<Canvas>> summons { get; private set; }
...
public void ClearDataAndDestroyInstance()
{
foreach (int i in Enumerable.Range(0,summons.Count-1))
{
foreach (Canvas canvas in summons[i])
{
Destroy(canvas);
}
summons[i] = null;
}
summons.Clear();
summons = null;
Destroy(Instance);
}
Is something like this too much?
I get trauma from programming in C in college
Now I'm implementing my IDestroyable on every class in my project hahaha
C doesn't have a garbage collector, so you need to manage memory manually. C# and unity does, so you just need to be aware of GC rules.
This sounds like an unnecessary overhead
you surely dont need to set every index to null, call .Clear() AND set it to null.
Honestly dont think you need to do any of this. Its pretty sufficient to just check for null before doing what you want.
This also looks like an unnecessary overhead to me.
Ok
I guess I'm only gonna be careful when around my instantiated SOs
Making sure to delete ALLL of them when my game session is over
you really dont need to instantiate SOs. You're doing this because you dont want to simply make another class and let the GC handle this for you
but what's the problem with this tho
I googgled it and ppl only told me to be careful with destroying my SOs
now you're in uncharted territory because you dont understand some downsides to it. This is just gonna take you longer than the 1 minute of setting up another class. Like "the game session is over" why does it matter what you do with your instantiated data
I dunno, It just feels right to code like this
Everything has been an uncharted territory so far
I'm just doing my best to manage my anxiety
a common mistake beginners somehow think is things are better because there is less code. Consider that this couldve been all avoided if you decided against instantiating SO's. And you wouldve already been coding another feature
just a note, when the game ends, everything is destroyed. its not just dangling around in memory if you dont destroy it past the lifetime of the application