#💻┃code-beginner
1 messages · Page 137 of 1
again, it only shows the editors you actually have installed. if you are using Visual Studio 2019 then you should be following the instructions for visual studio and not visual studio code.
there is absolutely no issue with it only showing the editor you actually have installed
I use the StopAllCoroutines method but the ai seems to be chasing the player but at the same time following the path of its patrolling waypoints, it doesnt chase in a straight line
what does the doesnt chase in straight line have to do with corouitne
but if you want to clean up your behavior def go with FSM
you still should learn how to manage coroutines properly
then i will just go ahead with fsm because coroutines are giving me a headache
I want to but I am still a complete beginner
There is nothing diffcult about them
its just a method, the only thing you have to keep in mind is that every StartCoroutine creates a new coroutine regardless of how many are running
youtube tutorials do help but they arent really complete but I will still search
can you clarify a bit more if that wont bother you?
If you call StartCoroutine(SomeRoutine) and then immediately call StartCoroutine(SomeRoutine) the line after, there are now two coroutines running that have absolutely nothing to do with each other
It will not stop the previous one and restart it
oh I see now
Ideally you would store it in a Coroutine
https://docs.unity3d.com/ScriptReference/Coroutine.html
(the docs is a bit unclear on how because it uses IEnumrator variable 🙄 )
or put a bool
exactly, thats why I came to ask here
vertx's site to the rescue with better documentation for StopCoroutine https://unity.huh.how/coroutines/stopcoroutine
anyways thank you people, I will continue to try to get a hang of them but I will also use state machines for my AI because ive been trying different things for 3 days and I dont think its that hard to make an AI
state machines and coroutines are not mutually exclusive. in fact you can think of a coroutine as individual state machines
Ok I will give it a read
I will look into it, hopefully I can pull off an AI thats better than Redfall's AI
because I definitely havent seen worse
I dont know if u care, but in case you do the projectile was too fast for the trigger to register. So all I did is use an OverlapSphere to check for all triggers hit when it got destroyed by the the actual Collider
hey guys, can someone please help me find where is the setting to mask 2d trail renderers? i need to set it to 'visible inside mask' but I cant find the option in the inspector
not enough information to understand what's wrong, you probably don't have the conditions for it to NOT switch back
obviously bcs the tutorial person has other IDE's installed, is my guess
The Red Class needs a reference to whatever class that Red function (the 'void' is in).
There's different ways to go about it, but easiest is probably to make a SerializeField in your class:
// (top of your script)
[SerializeField] ThatClassNameWithTheRedMethod colorChanger;
private void Start() {
// Your stuff...
}
private void Update() {
// Execute the 'Red()' method inside the specified instance of the class that contains the method, from this script.
colorChanger.Red();
}
Now you can drag and drop any object carrying the class containing the 'Red()' method, in the editor, when selecting the object carrying the class above ^.
In your other class, make sure the 'Red()' method is set to 'public'!
public void Red() {
}
If you don't want to have the class containing the method to be on an object, look into static classes or methods in C# and Unity.
this is the only code that changes the peramater
if (Input.GetKey(KeyCode.S)){
playerAnimator.SetBool("holdingTheDownKey", true);
}
else{
playerAnimator.SetBool("holdingTheDownKey", false);
}
}```
you probably have something wrong with the arrows that indicate which animation will be turned on, that is
Anim A --> Anim B
Anim B <-- Anim A
Anim A --> Anim B
...
no that is not it, it has only one arrow pointing at it. Is it maybe because of the animation being too short, or maybe because of a setting in the arrow?
can prefabs mess with movement that works like this
``` step = speed * Time.deltaTime;``
Maybe you don't have a looped animation and you have a checkmark for switching after the end of the animation?
because im using them in a different script to change the multiplier for an enemies health and the speed is somehow sped up
how do I check for that?
Wait for me to open the unity
press on your animation file, its in the inspector
Are you moving using Rigidbodies or just setting positions?
just transform
And is the value of 'speed' the same in both instances?
transform.position = Vector3.MoveTowards (transform.position, target2.position, step);```
this is how its used
Unity overwrites the script value with the editor value, in case you set it from the editor.
do they both run on the same script i assume?
theres no other script on them also causing movement?
oh
so they dont have the same script on them
it was fine then i introduced difficulty chosing and it broke movement if difficulty is selecred
so the movement is in the enemy controller
then ive got this in the player controller
if (PlayerPrefs.GetString ("Difficulty") == "Easy") {
mult = 1;
}
else if (PlayerPrefs.GetString ("Difficulty") == "Medium") {
mult = 1.5f;
}
else if (PlayerPrefs.GetString ("Difficulty") == "Hard") {
mult = 2;
}
else{
mult = 1;
}```
where do u use the mult var
if (other.gameObject.CompareTag ("basicEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 10 * mult;
StartCoroutine (Red ());
} else if (other.gameObject.CompareTag ("advEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 20 * mult;
StartCoroutine (Red ());
} else if (other.gameObject.CompareTag ("Spikes") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 30 * mult;
StartCoroutine (Red ());
}```
ive been told its poorly formatted but this is the best that the auto format does on monodevelop
ah but mult only changes the damage so it shouldnt impact speed
yeah
but the speed only ever messes up when i use the difficulty porefab and works fine without
ill send it in 2
Maybe have it so that it only changes on key down or key up (it seems to be calling the change too often): if Get Key Down Set bool true else if Get Key Up Set bool false
ahh, so i check if HasExitTime is true?
ohh yea that makes more sense
public class PlayerHealth : MonoBehaviour
{
public float currenthealth;
public float totalhealth;
public SpriteRenderer sprite;
public bool dead;
EnemyController enemyscript;
PlayerController playerscript;
public Slider HealthSlider;
float mult;
void Start ()
{
totalhealth = 100;
currenthealth = 100;
dead = false;
enemyscript = GameObject.FindGameObjectWithTag ("basicEnemy").GetComponent<EnemyController> ();
playerscript = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerController> ();
if (PlayerPrefs.GetString ("Difficulty") == "Easy") {
mult = 1;
} else if (PlayerPrefs.GetString ("Difficulty") == "Medium") {
mult = 1.5f;
} else if (PlayerPrefs.GetString ("Difficulty") == "Hard") {
mult = 2;
} else {
mult = 1;
}
}
void Update ()
{
if (currenthealth <= 0) {
dead = true;
}
/*Healthbar code*/
HealthSlider.value = currenthealth;
}
public IEnumerator Red ()
{
sprite.color = Color.red;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.white;
}
private void OnCollisionEnter2D (Collision2D other)
{
if (other.gameObject.CompareTag ("basicEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 10 * mult;
StartCoroutine (Red ());
} else if (other.gameObject.CompareTag ("advEnemy") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 20 * mult;
StartCoroutine (Red ());
} else if (other.gameObject.CompareTag ("Spikes") && (playerscript.voulnerable == true)) {
currenthealth = currenthealth - 30 * mult;
StartCoroutine (Red ());
}
}
private void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.CompareTag ("Healing")) {
currenthealth = currenthealth + 20;
StartCoroutine (Green ());
Destroy (other.gameObject);
}
}
public IEnumerator Green ()
{
sprite.color = Color.green;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.white;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.green;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.white;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.green;
yield return new WaitForSeconds (0.1f);
sprite.color = Color.white;
}
}
thats the whole thing
!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.
you could also send it as file, there'll be a collapse button haha
No, if you want it to be looped, check the box and make it turn off under a certain condition
use links for large code
damn
I checked it and the LoopTime is checked off
turn on and off when needed
if it is a walking animation, it should be looped
!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.
ohhh it works! Wait what does LoopTime do?
what is it for?
https://hatebin.com/qbyqfizerf thats the enemy code @slate gale
if your animation ends, it just stops and that's it, but this way it will constantly repeat
ahh I see
how do I do an if statement to see if the game object is active or not? https://paste.ofcode.org/CXruPysAbHcmXeViRY5pfG
Who's hating on what? 
well thank you
people mad cus they cant rotate their scroll wheel is all
nothing much\
i dont see much issues, but i see you set step to timedeltatime * speed in void start, but that wont do much
i think u need to put step in update
timedeltatime gets the time between past frame and current
what can cause those artifacts? It has something to do with player follow camera. THis thing looks like a sphere and everything on it's edges is getting blurred or distorted and it also gives everything within a metallic shine
maybe that void start runs at another time e.g. when u instantiate it and the frame time will be different and cause issues
@ivory bobcat the guy was just lurking chat to run the !code command, is what im talking abt
📃 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.
kinda extreme imo
Maybe you have screen blur turned on in the post process?
What can be the issue if my game crashes on startup but didn't crash on another binary?
My game works as windows x64 on my Windows ARM64 PC, but using the Windows ARM64 version of my game on my Windows 11 arm64 System make it crash in the mainmenu after 0.1 seconds.
Any idea why?
it's not blur per se... it's more like spherical distortion. Idk it bends textures... Where do I check?
ya got some ghost sphere haunting your scene
god bless you @slate gale its worked
not really a coding question though
lmao honestly didnt expect it would hahah
gg mate
happy programming
Oh, it's hardly related. You'd probably be better off asking these channels #archived-lighting #archived-hdrp or #archived-urp
Seemed appropriate. There were practically two messages posts, both above 12 lines - message flood. Nothing new 🤷♂️
thank you
im not saying it was inappropriate, just a bit weird the guy only joined chat to say that message, and besides, it wasnt busy no one was rly bothered by it.
but yes it was a long code snip
couldve been shortened or put in link but since it wasnt busy at the time i didnt think it rly mattered, is all
anyone know a good tutorial or fourm post on snowboard movement?
it isnt readind the magazineSize and bulletsLeft, but it displays at a 0.
sweet pfp
same
Hello
how come the first enemy i instantiate works fine, but the ones i instantiate after its death dont do anything
Because your script is only updating the first enemy
Why is the enemy behavior on the script that spawns them
You set enemyInstance to the first enemy, then immediately overwrite it with the second enemy
what would you have done differently
Why are you dividing botth values your trying to display? Its possible the division is resulting in a decimal that gets rounded to 0
why does WasPressedThisFrame() return nothing all the time?
this diddnt work for me
This wasn't a suggestion I was pointing out what you were literally currently doing
why
I don't know I was hoping you would tell me
oh ye thats because i wanna spawn two enemies
Okay so why do you immediately overwrite the reference to the first with the second
You are only calling Destroy on the second one
how do you know it returns false all the time?
wait a minute
ah nevermind
it actually works
its just the output that doesnt work
for some reason
I think I have an issue with an option or selection unchecked, but maybe it's my code?
My problem is that I have a UI button that, if I click it, then become the "target" of my character's Interact action until I click on the gamemap to "unset" the button somehow being selected.
public void OnBuyCropButton(CropData crop)
{
if(money >= crop.purchasePrice)
{
PurchaseCrop(crop);
}
}
void TryInteractTile ()
{
RaycastHit2D hit = Physics2D.Raycast((Vector2)transform.position + facingDir, Vector3.up, 0.1f, interactLayerMask);
if (hit.collider != null)
{
FieldTile tile = hit.collider.GetComponent<FieldTile>();
tile.Interact();
}
}
public void Interact ()
{
if(!hasBeenTilledAlready)
{
Till();
}
else if(!HasCrop() && GameManager.instance.CanPlantCrop()) // if you don't have a crop and you can plant a crop
{
PlantNewCrop(GameManager.instance.selectedCropToPlant);
}
else if (HasCrop() && currentCrop.CanHarvest()) // if you have a crop and it's ready to harvest
{
currentCrop.Harvest();
}
else
{
Water();
}
}
is there some setting to "unselect" a button after you have pressed it?
maybe it's a quirk with the new input system and choosing <Space> as the interact button?
how do you know? specifically what debugging steps have you taken to see whether your moveSpeed variable is the value you expect it to be?
i used debuglog the waspressedthisframe return value every frame
is for burst weapons and i am diving by 1, and even if i dont divide it doest show
and it returns some trues when i spammed shift
i would just like to know how to have the new enemies i instantiate work
so now i know its actually giving input
it just doesnt change the speed
i gotta figure out why
WOW
my dumbass set sprint speed and walk speed to the same variable
If you want this script to control those enemies, you need to reference both enemies
But honestly why does this script actually provide functionality to the enemies? It should just spawn them and they should have scripts that handle their own behavior
i have been having issues with scripts attatched to enemies
dont know how 2 manage it this is my solution
You're having issues without scripts attached to enemies as well
lol
So maybe you should do the one that makes sense and fix that
instead of trying to fix the one that doesn't
if i were to attatch this script to the enemy
how would i do the references in the editor on its prefab
You don't attach this script to the enemy, you have the script that makes enemies and the script that tells the enemy objects how to behave into different scripts
i know that part
i am so close to making my script work tho so i wouulld like to fix that if its possible instead
Hmm, are you certain that block of code is running and your text is updating? If you typed something specific instead of your variables, does your text reflect that? If so, then are you certain your values are both above 0?
yes from both
the magazine size updates on the inpector
Are you calling that logic from Update?
i dont think so
hi Peter
the 3th one here
Ah, if your changing the value from the inspector, youll also need to update your text, unless your initially setting the value before entering play mode (you also seem to have many clones today)
humm let me try it
i put it like this and still it does not work
What
Does that even compile
it's gross to look at, but it is perfectly valid
I guess it's like a multi-variable declaration, but only the first one gets a default value?
i was testing if it works
Can anyone who knows DOTween help me?
I'm super confused about some unexpected behavior. The first tween works as expected, however the next two somehow SKIP the index (if the first one tweened index 0, the next 2 tweens index 1), even though I've verified i = 0 before and after all three of those tween statements.
for(int i = 0, i < numNeeded, i++)
{
objectToTween[i].transform.DOLocalMoveY(myTargetVector3, delay);
DOTween.To(() => objectToTween[i].transform.position, x => objectToTween[i].transform.position = x, newPosition, delay);
DOTween.To(() => objectToTween[i].Color, x => objectToTween[i].Color = x, newColor, delay);
}
Yes I know I'm using the generic way in the last 2. It's because I'm actually tweening values that aren't supported in DOTween's shortcuts way' (Vector3 and a Color value not attached to a MeshRenderer). I changed the two because I thought that would be too confusing to see in the code
Ahh, good old lambda variable capture fooling people again
I will never stop stepping on that rake
there's a single i variable and it lives for the entire duration of the for loop
The bane of my existence
everyone is capturing the same variable
i remember writing a long post on the unity forum explaining why this is totally impossible and there must be something else wrong
then i tested it
egg, meet face
Really? my canvas is always way bigger then the camera size
yes, that's because it is a screen space overlay canvas and has nothing to do with the world size. a screenspace overlay canvas will draw directly to the screen and does not rely on the camera's size or viewport
I HATE WIZARDY MAGIC COMPUTERYNG, aparently restarting the program 3 times fixes it
how should i fix it
make your camera a normal size again
and check the docs pinned in #📲┃ui-ux to learn how the canvas works
Jeez, I would've NEVER guessed this is a thing!! Changed the 'i''s to a local integer variable and it works as expected! 😭
it's a surprise tool that will hurt us later
I need to get around to properly learning what the heck lambdas really are
All I know is I get angry when I see people using them, because I feel they're ugly and I don't understand them lol
is 200 a normal size
dear god no. normal is around like 5 assuming you are referring to orthographic size
It never stops. I've been programming for 20 years and I still lose entire days to this exact problem.
keep in mind that typically 1 unit is supposed to be 1 meter in world space.
orthographic size is just how much can be seen by the camera at once
OH NO!! 🥹
If your game makes sense when your camera view is 200 meters wide, then use 200
But I doubt that's the case here.
Oh alr i had put the canvas on Screen overlay thats why it was way bigger i think
again, the apparent size of an overlay canvas is not meaningful
it's getting drawn directly onto your screen; your camera's position and size is not involved at all
It's a common error to try to move the camera to "see" it
guys is is possible in unity to change the HDR and Fog color setting using dropdown you choose a different color and it changes
You can serialize a Color on the editor
but i want to do this using code
yes
like in the dropdown in the screenshot
Is the drop down box your implementation or an example that you're aiming for
You'd want to use the drop down via UI
make yourself a set of colors and plug those values into it
you will be using a TMP_Dropdown
that's what i did
you give it a list of options; you can then check the currently-selected option and make a decision based on that
how do I access a bool variable from a different script? nothing seems to work
how do i code health in a game?
With numbers usually
Why would health be a global variable
Lookup a tutorial. It depends on what your task is.
i was thinking how can i access a variable in another script?
tada!
oh
thanks fen
and ah i should say thank you to you two digiholic and dalphat for helping regardless
The big idea is that you need to get a reference to the object you want to get a value from
you might set this up in the scene by dragging an object into a field in the inspector
or you might find it at runtime with GetComponent
if the component I want to get a value from is called Foo, I might do this:
[SerializeField] Foo myFoo;
and then drag an object from the scene into the "My Foo" field in the inspector
then, if I want to get a value that Foo has ...
public class Foo : MonoBehaviour {
public float money;
}
...I can just write:
myFoo.money
📃 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.
why is the score almost always equals to 1 https://paste.mod.gg/jhlmvdufloiv/0
A tool for sharing your source code with the world!
Show us the console tab
So score incremented five times.
Either they were different instances or reset multiple times.
all 5 times are diffrent instances its flappy bird game
So every instance would have their own score and each would have a starting value of zero.
yeah
👀

So it's working as expected. 5 different instances each have their value increased by 1
So maybe have only one instance of score?
So they all have 1
not really shouldnt it go 1 2 3 4 etc.. since im using Score++;
They are different instances
If I have a dollar and you have a dollar do either of us have two dollars?
how do i make it a same instance
Which one's score do you want to increase
i want it to increase each time it exsits the collision
Decouple the score variable to a different script and reference the single instance. A new score should not live with each of these five instances of this script.
Which object's score do you want to increase?
Either that or the dirty solution of a static variable Score
the score is attached to the object in between the pipes that detects the collisions that is also the parent to the pipes
how do i make it so that there is only one instance of a class that can be accessed across scripts?
i want to do this so that i can implement a health system
So each set of pipes has their own score
The singleton pattern but that's not how you should be handling health
how should i handle health?
On the object that has health
Is the static property that turns GameManager global for all scripts or is it the acessor (get return)??
Detach the score variable from the triggering script. Make the script reference the single score in the game and increase that single score's value.
using Singleton*
Sorry to be still still bothering you but are you talking about something like this https://www.youtube.com/watch?v=hKGzSYXPQwY he starts talking about the points in about 4: 40
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Make flappy bird with this quick Unity tutorial. We'll even manage to squeeze in a highScore system by the end!
Download The...
...get return?
That is a property
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
hmm sorry I dont understand what it says
like get okay to get the property value of instance
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors. This feature enables data to be accessed easily and still helps promote the safety and flexibility of methods.
static would make the member a part of the class and not other instances of the class. You'd use it with singletons to ensure that each new instance of the class destroys themselves if the member isn't null. Wherever the class is accessible by code, the member belonging solely to the class can be accessed - new instances of the class will not have their own instance of this member.
who is the member
The variable (property)
What does Argument2: cannot convert from ‘UnityEngine.Vector3’ to ‘float’ mean
You've got a vector 3 there but they expect a float
what i dont get is what the acessor is for then
What part of it? Read but no write?
maybe what I am missing is what is the acessor exactly
To prohibit others from changing it but give others access to it to see if it's null or use it.
function takes a float, but your variable is a Vector3, so the program doesn’t know what to do
but the acessor is the whole
static private GameManager instance;
static public GameManager Instance
{ get { return instance; } }?
Accessor's are public, private, and a few other more esoteric ones you probably won't ever use
oh okay
I got my terminology wrong, ignore me
I was loosing my mind
Accessors are the stuff inside the get of a Property
I don't get your question or concern. This might be due to lack of c# basics. Format is generally [accessor] [type] [name] (let's not mention attributes)
could you point it out in this code I sent?
Maybe is a matter of translation, in Spanish when we do a Singleton we do an "Accesor"
which I THINK is this part
static public GameManager Instance
{ get { return instance; } }
that is the entire property
Singleton is a pattern (multiple things put together to accomplish a task). The keyword accessor is a c# keyword for who can read and write to the member.
would just ataching the script to the bird and changing the CompareTag("Player") with CompareTag("PointDetector) work
Probably not. You'd need to acquire the score component/script of the bird then increase it.
okay so, in that pattern what does this part do exactly?
It creates a static property that holds a GameManager object, is named Instance, and has a getter that returns instance
It was linked before what a property was, which should go over it's parts #💻┃code-beginner message
but wasnt a variable a property?
idk why but it somehow worked
no. properties are special methods that just look like variables. they expose variables to other objects using their getter and setter
Properties are things that can be used like variables, but are actually functions
example?
this is an example of a property
the whole line?
Everything
An example of a property:
#💻┃code-beginner message
but it is getting the private quality of instance?
that property is the equivalent of this:
private static GameManager instance;
public static GameManager GetInstance() { return instance; }
but instead of using a method called GetInstance, you just use the property which-again-is just a method that looks like a variable
oh oh oh okay okay
Im starting to see it
and why not directly using a public static GameManager
They look like fields but are actually functions under the hood. They can have backfields as well (with certain setups) making them functions plus fields, all in one.
You'd want to not give people access to the member directly, thus using a getter function or property.
because then anything can change the object stored in the variable at any time. properties are meant to control what can access a variable and how it is accessed
Consider asking yourself, why should you ever have private members?
Because I don´t want that everyone could change my code
And why's that?
||Because something wasn't meant to be changed and can break everything if changed||
does the order of scripts in a gameobject matter when calling (saying i call b's functions (being second script) from another object ,does script A get called first even tho another object called B (A is being called every frame)?
no
okay okay I see
Okay so by doing this I have made instance accesible from any script?
Anybody know a fix for an object's rigidbody returning wrong y velocities when they are moving on a composite tilemap? Or if there's an alternate known method out there that can create a physics collider shape via a script, without directly using a composite collider.
Anyone who has access to the type, yes.
whats the type?
you're gonna need to provide more context than that. what you mean it returns the wrong y velocity?
Game Manager etc
okay and then why is static used?
The class owns the member not the new instances
another way of saying it, is that static members are a part of the definition of what constitutes the class
Without static, every new instance of the class would have their own instance of every member. Not with the static modifier.. with the static modifier, there's only one member and it belongs to the class (the type - part of its definition)
with member you reffer to
example; Circle class might define radius (which is different for every instance), and static pi. Pi is just part of the definition of a circle, and is not owned by any one individual circle
radius (not static) is separately owned by each individual circle
Well, if I move the player left and right, when they are running on top of the tilemap with a tilemap collider 2d, and it's composite, the rigidobody 2d components shows incorrect values for the y velocity in the inspector, even though it's really supposed to just be 0.
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
It's particularly annoying when I need to do physics check that require it to be 0 or under, but the rigidbody "returns" incorrect values.
It shows 0 on regular colliders that aren't part of the tilemap's composite one, so I'm pretty sure it's the tilemap
and what is the actual value of the velocity when you check it using code? do not rely on inspector values
Okay okay, so with "static" I have made "instance" implicit part of the class and not of every instance of it right?
yes
so what is the purpose of this?
i assume you’re making a singleton?
yeah
If I do a check that let's say, turns a bool to true, and it needs the player to be on ground and have a y velocity of 0 or below, it holds true to the inspector values, so it works on normal colliders, because the y velocity is 0, but not on the tilemap
ok, that is how you make a class with exactly one instance
so you keep a reference to the ONE singular instance
which is better than making the whole class static if you want to be modifying variables
you said the Y velocity is not correct. what is the actual value it is returning when you attempt to check it via code where that actually matters. do not just look at the inspector and assume it is wrong because of what you see there.
show your actual code and provide the details if you want to get help
most of the things in my game where I need lots of things to access it, and there is guaranteed to be exactly one at all times, I make it a singleton
Alright, do you want me to use something like Debug.Log to return rb.velocity.y?
yes. you need to verify your assumptions
i think im more or less getting it but still I dont get what is its effect, sorry I´m beginner
wht is wheel colider
look at that, the velocity is such a small number it is effectively 0. now show the code where it isn't doing what you want it to
Don't use it if you don't know what it is 😆
Other than that, if you are only ever wanting one instance of something, you could restrict it with the Singleton pattern. Having pseudo global access to the instance field is just an extra - often abused and fine in game development.
Im learning it
Really just the part that checks rb.velocity.y <= 0:
if (rb.velocity.y <= 0 && isBallCheckCooldown <= 0 && unBubbleCooldown <= 0)
{
if ((isOnWater && Mathf.Abs(rb.velocity.x) > 18) || !isOnWater)
{
isBall = false;
if(rb.velocity.y > -1)
{
rb.position = new Vector2(rb.position.x, rb.position.y + 0.02f);
}
}
}
Should I be using a different method to compare the y velocity?
let’s say your game has a bunch of enemies. and you need one thing to keep track of everything. so if you want to wipe everything, you can ask this one “EnemyManager” to destroy every enemy. I would make EnemyManager a singleton, so every individual enemy can tell my EnemyManager that it is around. And each enemy tells EnemyManager when it dies to know not to count it anymore
Then my menu (or whatever) can tell EnemyManager to kill everything (like when I’m unloading an area)
there should never ever be 2 EnemyManagers. We are keeping a single log of eveery enemy, and we don’t want to mix and match and get two logs that aren’t properly synced
and it should not be static, because that has a ton of negative side effects we don’t want to get into
make sense?
!code 👇 and also why do you need to check that the velocity is less than or equal to 0 here on just the Y axis? knowing that could help improve what you are actually doing. but if you just want a bandaid fix without addressing the root of the actual problem, just use a slightly bigger number to compare it to like 0.001 or something tiny like that
📃 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.
yes, I get that
If it were a spawner and you're wanting multiple instances, you'd want to not opt for a Singleton but simply pass references or subscribe to callbacks. It's necessity is purely if you're wanting single instances. Ease of access should really ought to be a secondary charm.
okay so
to sum up
static private GameManager instance. I make this private variable
Thanks for the code command thing, didn't know about it. I'll try using a slightly larger number, but the reason I am making the check is the following:
Sonic's charatcer uncurls from the ball state when they land on ground. The player can also jump onto one way platforms where they will be grounded for a short period. I need to check if their y velocity is smaller or equal to 0, so they only uncurl from the ball state on the way down, and not up.
which creates a variable GameManager type
GameManager here is a class? an instance of the class?
what part of this code is causing unity to say "Assets\playerMovement.cs(22,57): error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector3' to 'float' " and how do i fix it?
what is it refereing to?
configure your !IDE and it will show you where the error is
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
ive tried but i cant find the error squiggles setting
i spent like all of yesterday tryng to, it sucked
if you cannot follow the simple instructions to configure vs code, then consider switching to a real ide like visual studio which is easier to configure and less likely to randomly break. but it is required to have a configured ide in order to get help here
yeah, im trying
Using the very small number seems to have worked. Thanks! I still find it strange that the issue was only present with the tilemap collider, but I guess not everything can be perfect.
it's just some floating point precision issues. same reason you should never compare a float is exactly another float, there may be some super tiny difference like what you were seeing where the Y velocity was 0.00000007 instead of just 0
Once you get it done, all of your syntactical errors will magically go away (it ought to even prohibit you from making mistakes by not being able to provide suggestions). Poorly copy and paste results will be underlined with squiggly marks. It saves everybody a lot of time.
yeah, thats cool and all but i just cant find where to enable it, ive tried every combination of google search it just does apear
Follow the guide. Determine which step you've gotten stuck at.
the guide hasnt helped, i can get to my setting n stuff, but it doesnt show the setting i need to enable
it gave me autofinish, but not error squiggles
Is this VS or VSCode?
i thing VSCode
So guys what makes that i can se the variable in other scripts is the get return public or the static????
ye VSCode
Wat?🤔
so in a singleton pattern
Public is access modifier it has nothing to do with static
Did you do those three steps? I'm assuming the first two were completed (installation of Unity and VSCode - differs from VS)
yep
static private GameManager instance;
static public GameManager Instance
{ get { return instance; } } in this code, what makes I can access instance from other script is?
So did you install the extension?
ye
that is what the public access modifier is for
Can you show us an image of the extension installed?
Ignore the static here, can you access private outside the class (usually)
where's the unity one
so you store the class in "instance" but how does that make that there is only one instance of the class?
i dont see the relation
Where's the unity for visual studios code?
also there
look up a singleton implementation in unity on youtube
Static wont change the accessibility of members
it told me to get those the first time i opened it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
static private GameManager instance;
static public GameManager Instance
{ get { return instance; } }
// Start is called before the first frame update
private void Awake()
{
if (instance == null)
{
GameManager.instance = this;
}
else
{
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
}
}
I have this
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Next, did you update the package for your unity project?
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
what do you think this is doing?
creating an instance allows you to access it from anywhere. you only need/want one instance of it or you can get errors that why you check if the instance exists and destroy it so you dont make two of them
Yes but I dont get the relation between this and that necesarilly instance has to be part of the class and not the instance
what could happen if "instance" was part of the instance and not the class
i was not answering your question, i was legitimately asking what you think those two lines are doing together like that. why are you passing the gameObject to DontDestroyOnLoad right after you destroy it
It wouldn't be the Singleton pattern and you wouldn't be able to access it without an instance of the class.
Instance is not a part of the class, what is stored in the static field is a reference to an instance.
i think so
remove the highlighted package
what?
It should be "Visual Studio Editor"
I think you need to go over the OOP basics in C# context. You need to understand what type, instance, reference and static are.
Remove the older code one above
I know what they are bro
Static members are members of class not the members of instances of class
Doesn't sound so from your questions.
okay I get that
k, it did tell me some other thing needs it tho so ¯_(ツ)_/¯
but why is that necessary for the Singleton to work
Because singleton implies static access to an object.
nvm, it just wont let me remove it
believe me, I know what they are
You can ask the class to return an instance of that class for you and you dont care where the instance comes from
After you finish, setup your external editor configuration in Unity
it already uses that one, and when i go to remove the VSCode Editor, or the VS Editor it wont let me cuz they're necicary for some other thing
unlock the engineering group then you can remove the vs code editor package
in short, it's not, it's just an implementation detail to make it easy to access the singleton instance of a class through the class itself
It's a part of the pattern.
but it should have its explanation right?
It's not a pattern isolated to unity itself. Searching should give you lots of results.
did that, its still telling me its a dependency and i cant remove it, but the external tools thing says that 2.0.22 is enabled so
Regenerate the project. Does everything work now?
nope, theres still no error squiggles, and i have the same error msg
Well, we know where the error is, it's very obvious. Were there any issues when restarting VSCode?
Any pop-up in the bottom right?
yeah, these
Right, so Net SDK is missing
Here's a tutorial that goes over everything you've done so far and a bit more https://youtu.be/-AgcVsS-rtQ?si=yo27AvkRd3eBgci9
In this video you will learn how to configure Visual Studio Code for Unity development. You'll learn how to get many things working including syntax highlighting, debugger, auto formatting, and snippets.
thx

can someone help me out here? what i want to achieve is that the Instantiate snippet of the code gets done once the "Fire2" Axis is released. what am i doing wrong?
i think get axis raw gives u vertical and horizontal inputs
are u looking for GetMouseButtonDown?
when I use a camera to render a texture, how should I handle camera size? I was trying camera.orthographicSize but even if I set a default value on inspector, it sets back to 5 when I hit play
What's happening right now?
I'm assuming it happens immediately or all of the time.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I cant read screenshot image well 😦
it gives me 1 if pressed or 0, when i put the Instantiate snipped into the "if (Input.GetAxisRaw etc) section, it works. however im guessing that its something with the drawTime timer that doesnt work properly
are you using Cinemachine
nop
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is my camera, if it helps
As I said, when hitting play 'Size' jumps back to 5
well that screenshot was taken in play mode
if it happens when you enter play mode then you probably have some component assigning it to 5 in Start or Awake
it doesn't really answer the question about cinemachine, but I suppose u havea script then doing it
wym?
I have a script it is only 1 line of code
m_camera.orthographicSize = 1f / m_camera.aspect * unitsSize / 2f;
I have the same script attached to another camera and it assigns it 10.27778 due to screen dimensions
show the entire inspector for the camera object that is being affected by this issue
why is Fire2 an axis?
8.888882 is my default value, before I hit play
not really useful because script should set it to 10.2777
is Camera Size the only other component attached to that object?
it has another component
because all inputs are axes in the old input system
but it doesn't do anything with camera size
show the contents of both of those components using a bin site
how did you manage to find a bin site that terrible
i can remove camera shake component from the affected camera
lol
in the future please use a site that has line numbers and syntax highlighting. the bot has several in the !code embed below 👇
📃 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.
no they should just be Buttons..this would make it easy with a simple GetButtonUp method
but try changing the camera's tag. i'd bet you'r accessing Camera.main somewhere else and it's affecting this camera since it has the MainCamera tag
I'm sure those scripts are the oly ones that handle cameras
anyway I did it
nothing happened
wdym nothing happened? nothing as in the issue persists or nothing as in the camera's orthographic size was not changed to 5?
check anything that references it
well then either your math is wrong or the aspect property of the camera is not what you are expecting it to be.
or you are referencing the camera somewhere else
math is ok because same script works perfectly for main camera
well then i guess there's nothing wrong. good job fixing it
basically I just cloned main camera
but I think it has something to do with render texture
because camera becomes square
and it's the only thing that differs from main camera
so then like i said "the aspect property of the camera is not what you are expecting it to be"
and that means your math is wrong
enable only appears when MB callbacks are use
eg Update/ Start etc
dang, never knew this was an option, yeah it works
it has awake
what does MB mean?
Awake is not affected by the enabled state of the MonoBehaviour
MonoBehaviour
so is it wrong?
is what wrong?
should I change it to start instead of awake?
why
its probably a super simple fix that im not seeing but how am i sposed to fix this?
rb.velocity.y
well rb.velocity is a Vector3. you cannot have an entire Vector3 in a single axis of a Vector3
thx
also its important to read the errors they usually hint to the problem
yeah, i do, im just kinda dumb
eh with time it will become clearer
my thoughts exactly, i only started trying making games yesterday, and i think its going well so far
well goodluck! a least ur ide is configured so you're pretty much ahead of most xD
i only just did that like 15 min ago
every victory counts 💪
fr
I'm working on a small state machine, and I'm struggling with understanding how to pass one variable between different files. do you need a new instantiation of the class the variable comes from in each file it's used? And would I need to use the same name across files?
Also I'm not really understanding when you need to use the new keyword. how come sometimes I see someone set
SomeClass name = new SomeClass();
but sometime I see someone write only
SomeClass name;
all the struggles will be worth it when i make some really cool thing down the line, i mean just getting a white bean to move was cool
references
btw you only instantiate class like this, when its a regular class and not MonoBehaviour
is this about the top or bottom code snippet
top
is it possible to stop the animator from animating a gameobject on a certain layer?
"on a certain layer"?
like, when the GameObject is put onto a specific layer?
(rather than animator layers)
I mean the animator layers. I know theirs stop playback but that stops all animations
Hey guys. Quick question. I have a unity script on my player for player movement. Everything is stored in methods. Well I call the methods and using a Debug.Log I determined the methods do get called but. chaning my velocity variable doesn't actually change the variable. However if I reload the script BUT LEAVE GAME RUNNING it will work? It is like the script is not loading properly. is there something I can do to make sure a script loads properly or what am I doing wrong
show relevant code and logs
Ill post in a bit. I am away from my unity. was just wondering if maybe this was a common issue
thanks anyway though
Can I get suggestions to learn c# scripting
there are beginner courses pinned in this channel
I think it is not necessary to just learn and remember everything we need to just understand the code
Because I am having a lot of problem in writing script
Although I have cleared by basics of c#
Every time i get something new and I don't know how to remember it
you remember it by doing it over, and over and over and over
Okayy
There's really not much remembering. There's understanding and reassembling the blocks yourself every time since you know what they all do
Also try taking notes, having a notepad open as you follow tutorials or script in Unity, and write down things that confuse you, things you search up etc so you have a reference point that makes sense to you that you can refer to, I find as you work on code its less about memorizing, and more about recognizing patterns, like seeing "null reference exception: object reference not set to an instance of an object" ive seen enough times I usually know what "object" is null and why
Hey everyone i have a problem with my code that only happens when i run it twice
typeWriterAnimation = LeanTween.value(0, text.text.Length, text.text.Length * 0.05f / _text_speed).setOnUpdate(length => text.maxVisibleCharacters = (int)length).setOnComplete(_ => hasTextRolledOut = true);
I get a NRE but only when i play it twice
I recommend taking physical notes on paper. Helped me when learning anything new
Also allows you to review the material in your own words
📃 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.
Gotta provide more info. What throws the error? Can you take a screenshot of the error details?
What is DialogueUIManager line 123
typeWriterAnimation = LeanTween.value(0, text.text.Length, text.text.Length * 0.05f / _text_speed)
.setOnUpdate(length => text.maxVisibleCharacters = (int)length).setOnComplete(_ => hasTextRolledOut = true);
I'd guess that text is being destroyed at some point while the tween is still running.
This worked thank u !!
So I've got two scripts, one is the player script and the relevent code from it is
audioManager.PlaySoundFX(deathSFX, deathVolume);
level.LoadGameOver();
Destroy(gameObject);
}```
Now the level.LoadGameOver(); it is referring to has this following code.
``` public void LoadGameOver(){
//SceneManager.LoadScene("GameOver");
StartCoroutine(GameOver());
}
IEnumerator GameOver(){
yield return new WaitForSeconds(1);
SceneManager.LoadScene("GameOver");
}```
The problem is that when Death() runs I get the following error.
```Coroutine couldn't be started because the the game object 'SceneManager' is inactive!
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Level:LoadGameOver () (at Assets/Scripts/Level.cs:10)
Player:Death () (at Assets/Scripts/Player.cs:108)
Player:ProcessHit (DamageDealer) (at Assets/Scripts/Player.cs:102)
Player:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/Player.cs:94)```
I've tried adding debug's and a debug in any method other then the coroutine shows up just fine. Additionally if instead of using a coroutine to delay the scene load I just load the scene from the LoadGameOver() method everything runs fine. I have also tried using
Debug.Log("Scenemanager received the command to start the coroutine");
if (gameObject.activeSelf) {
StartCoroutine(GameOver());
} else {
Debug.Log("The scene manager is not active for some reason");
// Additional error handling or alternative action if needed
}
}```
And the first Debug.Log will get logged but then it's like unity ignores the rest of the code and throws the exact same error. I've been stuck for a while and would appreciate any ideas.
When do you call load game over?
Second line of Death()
Show us the console logs. You've got some race conditions with objects already destroyed attempting to run coroutines.
Everything the console logs other then my Debug.Log statements is posted. or did you want the Debug.Logs as well.
Are the scripts containin Death and LoadGameOver on the same object?
No
Show the full !code of both scripts
📃 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.
Add this code to the Level script:
void OnDisable(){
Debug.Log($"{gameObject.name} has been disabled");
}
Keep all the other logs you put in. Then show the console leading up to the error
I don't think the scene manager is actually ever disabled. The disabled message only showed up when I stopped the game
Thinking about it, this script setup was working just fine until I moved some of the Players stats out of the player script and into a PlayerStats script. Could that cause something like this?
Do you have "collapse" toggled in the console?
If so, disable it and make sure the order is what you think it is
it was enabled, I disabled it but got the same results
Are you sure you're not triggering the coroutine twice? If so, one of them would finish and change scenes while the other coroutine is still running
Would that result in a scene change? If so then that's not happening. If it is happening, the only cause I can think of would be if the player is getting OnTriggerEnter2D called multiple times at the same time. I could use a bool check in process hit to make sure of wether this is the case or not I guess
If the scene isn't changing then it definitely seems like the object is disabled when the coroutine tries to start
Did you try logging gameObject.activeInHierarchy before attempting to start the coroutine?
Then it's disabled.
Completely unrelated to any of the code here, the object is just simply off
enabled and disabled is the little check box to the left of the object name right?
Yes
Then I have no idea what I'm doing I guess, cause that box is checked on, and while testing it I never see it get unchecked.
What about it's parents
in order to remove them as a variable I took it out of it's parent and got the same results. but the parent is never inactive as far as I know anyway.
Send a screenshot of your full unity window, with this object selected and the hierarchy visible
I’ll send it tmrw, I have to go to bed tonight.
are there any specific tutorials you'd recommend, that you'd feel beginners could learn a lot from
imo Brackeys is the best unity youtuber for beginners. He makes everything very approachable and easy to digest. But, his stuff could be outdated, and he doesn't really go in depth. Once I felt like Brackeys wasn't cutting it, I watched Code Monkey instead. He's extremely active and makes a video on almost everything. He also goes very in depth and a lot of his code is good enough for production
What can I use Interfaces for?
How is it in relation to a struct?
No youtube code is good enough for production
An interface is simply a contract that enforces the implementation of certain functionality. A struct is a value type you define that can hold data and functionality
Definitely not, there's a ton of errors, misinformation, and just a lack of room to expand in his work. everything works purely for the purpose of the video, then you have people in here ask how they can add X functionality and it requires an entire rewrite. While also pointing out to them they shouldnt use deltaTime for mouse input
Assuming you're talking about Brackeys. From what I've seen, his videos are targeted for beginners, so there's definitely going to be a lot missing. I've noticed that his code can be improved on, but I can personally look past that if I'm a beginner. He's a great introduction and explains everything in a way that even a complete beginner can understand. Having millions of views for beginner Unity tutorials is impressive and imo seems to prove that he is very skilled at teaching beginners
It simply proves the all mighty algorithm chose him. Imho Brackeys teaches many wrong practices that stick with beginners
on top of what Uri said, he makes decent quality videos (visually) where it seems like he knows what hes talking about, this helps with the views. beginners wont be questioning anything because they dont have the knowledge.
Ive taught beginners, and i have doubts that anyone would really learn from his content. It will be people copy pasting then assuming they've learned. Imo if someone wants to truly learn, they should start with c# alone and not even do unity. Otherwise all "learning" will be fragmented pieces of code without understanding the fundamentals
just a question, is learning json and data persistence for the first time supposed to be overwhelming? It feels like a lot of information was thrown very quickly and that perhaps I won't fully understand it for a very long time lol
I wouldnt say it should be. The code itself is very simple, like maximum 10 lines for the entire reading and writing of a file.
You may just need to experiment more with it, and start with simpler cases. Try saving just a string for example.
learning json? JSON is a data format, very little to learn about it
as for File IO, the simplest of C# console programs should teach you most of what you need to know in an hour or so
well the concept seems simple, the execution just seems a bit laborious. Creating classes and instances of those classes across multiple scripts and then memorizing the json syntax on top of it. I guess it's just a matter of using it over and over to get familiar, I was just caught off guard with the sudden influx of information compared with the rest of the course lol
I'm sure no one ever told you that designing and building computer systems was easy. It does require you to absorb vast amounts of information and concepts of which you will be unfamiliar
it just takes time and practice, eventually it may become as natural as breathing
Memorizing the json syntax? It is simply a method call, which is the same syntax as most of what you'll do for using the unity api. And you dont even need to remember it, just Google it. No one remembers everything, we look at the docs all the time
tbf you don't even need to do that, Saving/Loading to and from json is pretty standard so you write your own utility method to do it then you only need to remember that you wrote it
many possible reasons
ANY compile errors
script not attached to an active game object
to name but 2
of course, how else would it run?
did you attach the script to the object it is cloning?
Think about it
CloneObject->Start->cloneobject->start etc etc until Unity him go bang
objects should not clone themselves
you put the cloning script on any gameobject except cloneObject
is it more efficient to find by tag or by layer? or is there a better way?
tag
better way is not to use Find at all, dependency injection springs to mind
not sure what your question is, explain
Realistically this shouldnt even be a consideration, if you're doing this on a LARGE amount of gameobjects then performance could be a consideration. In that case, attach the profiler and see for yourself exactly what the difference is.
You might not want to use a layer purely for the purpose of searching because then you must consider other things like camera and physics for every single layer.
Another thing is you shouldnt really need to do either of these as Steve wrote
typically your "original object" that you spawn clones of would be a prefab asset not in the scene at all
are you expecting the cloned object to be in the same position as the original?
also you should 100% start with some basic courses to learn unity. the pathways on the unity !learn site are a good place to start
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
that is prefabs as @slender nymph mentioned
ill check out the profiler and see how much my perfomance is hit, and go from there thanks.
i am doing a procedural generation level manager
should i make an another class for my custom window, or is it ok to use the same class where the generation logic is ?
custom inspector?
seperate class and put the script into an Editor folder
i'll do that
but this means that from my LevelGenerationManager class, i need to get the value of myWindow
because the goal is to trigger specific methods or set parameters from the custom window
for example:
in generate() inside LevelGenerationManager, there is a debug bool set to false by default, i want that before executing it get the values for the custom window
idk if its possible or even if its the good way
using the context menu was also another way, but i wanted to have a custom window rather that clicking on the 3 dots on my script component
that wont work, editor scripts do not exist at runtime.
what I tend to do is to use a ScriptableObject as a go between i.e. EditorWindow->ScriptableObject->Runtime class
i see what you mean, but i dont understand how i would do this
do you have any recommended ressources or page doc i could start to look at ?
sorry, no, I just do it
no worries ty for the help
#💻┃code-beginner message
please do yourself a favor and learn the basics
of course, you set cloneObject to your prefab in the inspector instead of the game object from the scene
btw box ty for running the array test
Ye
yes
Can you please learn basic c# and stop asking here
o damn
These type of questions should not be needed. The point of this channel is helping you with starting with Unity, not figuring out how c# works. There are courses for that.
Please try to !learn these things
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Wrong one, but you can also check the pinned messages for courses 😛
How can I make a wall go down like a door in 2d unity?
so when the player touches the key, the wall on the right goes down in a smooth manner
I already got the OnTriggerEnter2d method for the key but what code will make the door move?
lerp its position
what does "lerp" mean
https://unity.huh.how/lerp/overview
also you know google exists, right?
try spending more than 10 seconds using google next time 🤷♂️
alright, guess you don't want help then
I do, but I spent a large portion of time yesterday trying to find a solution, I even tried solving it on my own, and I spent like 10 minutes today googling again, it's pretty annoying when someone just tells you something like "try spending more than 10 seconds using google next time", I don't know about you but I don't like it when people talk to me in such a condescending tone, especially strangers
Finding out what lerping is is the most Googleable question I have seen in here so far
It's rude to say but very needed considering the amount of questions that come in these channels
oh lerping, I'm talking about googling the wall issue
mb
Thought he was telling me that I shouldve found about lerping through google
sorry
So the idea is that you trigger the wall however you want, and then adjust its position. Then using lerping you want to move the wall to this new position.
👍 thx
This could be done with a Coroutine
alr
guys, can you tell me how to fix this error?
Does your previous class, or those before it have a constructor
you need to include those params into all inherited classes via base keyword for each constructor they're included in
its there tho
usually if you right click on the error it'll do it for you
public CastableAbility(ICastableAbilitySO storableObject, IEntity entity) : base(storableObject, entity)
in the error list or on the part of code that is highlighted red?
Yeah, it'll have an option to implement them for you
similar to how you let the IDE auto implement interfaces for ya
Ah, maybe because you've edited the constructor already
wdym i still have the error
yeah, you still need to add base keyword
i dont know what that means
it's a c# thing where inheriting from previous class that has a constructor other than the default
you need to implement the same parameters in the inherited class like this ^
on what line do i do this?
nvm got it
Is there a way to easily get global co-ordinates of specific points within a scene?
I want to be able to easily place points within a navmesh (but within a certain boundary of said navmesh only),
Meaning maybe something like:
+--------------+
| A | | B | | C |
+--------------+
Maybe in phase 1, I only want points to be placed in region A. And in phase 2, only points be placed in region B (and so forth).
I am planning on raycasting from a greater z-axis to intersect with the proper z-axis on the floor and thus place points on the navmesh that way. But I'm having difficulties getting the global co-ordinates.
As an aside, are there better ways of going about this?
not entirely sure what you mean - a raycast hit is already in world space, as is transform.position - what are you doing that you think it isn't?
How are you currently "placing" points? I just put a empty gameobject around where I want things to spawn, the position of the gameobject is the global position
yes, the raycast hit is already in world-space
"global coordinates" would be world-space positions
what is the problem you're actually having? are things spawning at the wrong spot?
try NavMesh.SamplePosition
anyone know why this happens when using IDragHandler?
code:
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Begin drag");
}
public void OnDrag(PointerEventData eventData)
{
m_RectTransform.anchoredPosition = eventData.delta / canvas.scaleFactor;
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("Eng drag");
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Pointer down");
}
It happens because something is off with your OnDrag I'd assume ;p
Not sure what dividing by a scale here does for ya
A bit of a general question: How valid is the approach of using a static "Game Manager" vs. using delegates/events for my game? Is it strictly better to implement events? If so, why?
canvas scale is not 1 so its off when dragging, the problem was i had to do recttransform.anchoredpos += instead of =
You'll find it hard and design a game without utilizing events. They help keep your system(s) as loosely coupled as possible. Game managers (singletons) abound as well. Why not use both?
I need to cast from some xyz coordinate in world space, but i don't know where to cast from
Try Mouse.current.position.ReadValue(); or Input.mousePosition instead
in order to cast in the first place I need some xyz position to cast from. I can visually see where i want to cast, and mouseclick works, but i can't do it programmatically or at least idk how
ya but then I need to spawn the camera and move it around manually to cast it. My use case is to spawn many points programmatically within specific areas (A,B,C) during different phases
+--------------+
| A | | B | | C |
+--------------+
maybe i will spawn 5 points randomly in A during phase 1
then 20 in B during phase 2
etc.
how do you know what A,B,C are?
Actually if it's the event system you can just do transform.position = eventData.position, no?
I have a visual idea of where I want A,B,C to be
but idk how to derive it in the code
Hi Pals,
I'm a beginner with some experience in coding. I would like to know what's the best way to create a simple 2D board game like Rummikub with draggin cards feature and having a board which allow to placement from the player hand board the cards?
it sounds like you want to define what A,B,C actually are
Then you're going to need an actual definition of what those are
how??
create a position and bounds that defines them
like dude my navmesh is just 1 contiguous plane
how
Decide how you want to determine those regions and then do that
You need to formalize the rules, not just "I kinda feel it out"
effectively you spawn a cube, a cube is centered on a position and extends its bounds according to its size
ok
and now you can get the position of that cube
or whatever shape you want - you define the bounds
Like, is it dividing a mesh into thirds? Is it three regions of equal spacing starting from some point? What are the regions?
so i get the location(s) where that cube intersects my navmesh and assign that as the 'limits' for A,B,C?
You need to decide what they are
it's not equal thirds
this is an oversimplification
it's a navmesh
i need to divide my navmesh into 3 areas
which spawn 'pointobjects' during different phases
but idk how to get the boundaries for A,B,C
Okay cool so that's some information on how you're determining the region, just keep coming up with more of those until you actually know what you want
dude
i just want to know how to define it
in the code
or in the editor
why are you being condescending like this
do you know how to make a navmesh
That is something that literally only you can do.
your problem is kind of ill-posed
if you do then make navmesh 2 more times
So yes, one option is to just make multiple nav mesh surfaces
Because it is literally impossible for anyone but you to know how you want to define these regions
The first thing that comes to mind for me is to just make some box colliders
and to sample a random point inside the collider
i just followed this tutorial
Learn how to create AI pathfinding using the Unity NavMesh components!
This video is sponsored by Unity.
● Watch on Unity's website: https://goo.gl/jUsU8D
● Example project: https://github.com/Brackeys/NavMesh-Tutorial
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·································································...
it doesnt say how to divide the baked navmesh into the separate regions
yes, because that's a very specific task you're trying to accomplish
you probably won't find a tutorial that does exactly what you want
Another option is to have multiple nav mesh areas -- you can have up to 32 of them
Normally you just have walkable + non-walkable + "jump" areas
You would use nav mesh modifiers to assign different areas to different parts of your mesh
However, I'm not sure what would be an easy way to then randomly sample points within a specific area.
the player character/agent needs to traverse A,B and C
so i don't know if having different areas is the solution
they need to be able to cross A,B and C
but the points must be spawned inside those specific boundaries only
explain what you're actually making your game do here
not "spawn things on a nav mesh"
like, what's the gameplay here?
it's for determining randomized movement
no implementation details
i literally don't know what you want from me
I want an explanation of what gameplay you're trying to create.
it's not gameplay
i just want to be able to spawn points, maybe programmatically, maybe randomly, such that it can direct specific placement of some agent int he navmesh
the player agent can move through A,B and C regardless
"gameplay" means anything the player experiences in your game. the way goombas walk around in a mario game is part of the gameplay
but the other agents should be limited to A,B,C
Are you trying to make enemies that randomly wander around an area?
at the specific phases
yes but not necessarily randomly
like randomly may be strategyA
then linearly strategyB
then some other programmatic implementation strategyC
and so forth
a lot of things sound like a strategy pattern :p
so what am i actually supposed to do to divide the navmesh
okay, so each character is fenced into a certain area
and you need to be able to pick points within that area
by "you" I mean you, the programmer
lord help us
do you want to be helped
it should spawn like 20 points in a certain space
honeslty fuck you guys you are just trolling me for real
Lord give me the strength to not to throw a javelin through this man’s chest, for he does not understand the trials he puts us through, Lord
this is ridiculous. we're trying to help you and you're being combative.
My guy the computer cannot read your mind. I've already given you a simple and workable implementation above, if you have a question about that feel free to ask it, but at this point I'm not sure what you're even trying to ask.
If I have a function that I want to increment a value on a prefab, how should I go about referencing the prefab? Do I pass the name of the prefab into the function when I call it, and then change the value on the prefab within the function?
Do you really want to modify the prefab?
It's not invalid, but it is unusual
when you instantiate the prefab, you get a ref to the gameobject you just spawned
you definitely won't pass a name in, though -- you just reference the prefab through a serialized field, as you would an object in the scene
and since you instantiated it via code, you also already have a ref to the prefab
If you don't even know what you want how the hell are we supposed to know? There are tons of ways to define a region in code but step 0 is to know what regions you want to use
Derp — you're right, I want to modify an instance. 😎
it sounds to me like they want to be able to create a subset of the navmesh surface
imagine intersecting the navmesh with a cube
That's actually an interesting question. It would be useful for the game I'm working on right now.
and then use different strategies to define different movements on that navmesh
Right but how. All I know about the region is "it is not equal thirds"
ahahahah
What exactly do you mean by "get a ref"? The name you give the prefab upon instantiation?
Thing myThing = Instantiate(thingPrefab);
when you call Instantiate(prefab), the output is the GameObject you just made
thingPrefab is as reference to a prefab with a Thing component on it
myThing is a reference to the freshly instantiated Thing
var enemy = Instantiate(enemyPrefab);
enemy.health = 100;
Wait hang on I think this guy's game might be SCP-055
https://scp-wiki.wikidot.com/scp-055
We can only describe it by what it is not
The SCP Foundation's 'top-secret' archives, declassified for your enjoyment.
enemyPrefab being the name of the prefab being instantiated?
names are not relevant here
[SerializeField] Enemy enemyPrefab;
enemyPrefab is a field on our component.
it's a variable that's stored in the component.
the prefab could be named "Enemy" or "Glorbo" or whatever
enemyPrefab is the prefab
it’s the blueprint to make a gameobject that you keep as an asset file (not in the scene)
the gameobject is the actual instance that lives in the scene during runtime
A field of type Enemy can refer to any Enemy component
it could be one on a prefab, or one on an object in the scene
not sure it was that deep - think he literally just needed to manually place an anchor point for A and instantiate an object within a radius of it. Hard to pierce through that extreme beginner mental model of how a computer works though
That would be a simple option, yeah
basically sticking the enemy on a leash
Intersecting a navmesh with a volume would be really neat, though
I have an AI routine that searches for the player after losing sight of them
right now, it fires a bunch of navmesh raycasts in a circle and then randomly wanders inside that area
I guess I can just randomly sample points within a box to get the same result as some fancy intersection-with-a-volume, though
but that would stop the enemy from taking a long path out of the room into a neighboring room, since there'd be no path to the other room
Possible but until they tell us what they actually want all we can do is guess
they want the computer to figure out how to do it for them
Still learning about SerializeField; what exactly is that doing in this particular case?
It tells Unity that it should show that field in the inspector and remember its value
Unity automatically serializes public fields. You have to be explicit for anything else
Leaving fields private reduces the amount of clutter you see when other classes use the component
(To “serialize” is to turn a code object into data.)
serialized = is saved in a file
nice, there's a lot of subjective decisions to make with AI pathfinding like that, part of what makes it difficult to help as it seems like a beginner usually has an opinionated idea about how it should work based on some game they played, but can't articulate that in programming terms (or even describe it at all)
not serialized = not saved in file
yeah
by default, public fields in Monobehaviours and ScriptableObjects are serialized. non-public fields are not. If you want the behaviour to be different from this, you need to use SerializeField or NonSerialized
And what exactly is 'var' here?
var is a keyword to save some typing
var is a keyword to declare a variable without showing the type
When the type of a local variable is obvious, you can write var instead of the entire type
you should not use it, at all. Until you have a lot more experience
var x = 3; // x is an int
I think it's good to understand exactly what type you have, yes
I don't use it in this situation
i basically never use it.
It's handy in foreach loops
foreach (var module in modules) {
}
I sure hope I know what module is
i did that once. i thought module was of type IMyInterface, but i forgot module was of type SerializableInterface<IMyInterface>. Which didn’t throw a compiler error, but then makes everything super wrong
never again
splat
you've been missing the most used and loved feature not just in c# but in any other languages 😄
var is also useless if you need a less specific type, of course
until you come to read your code and then what?
i used to love that about python, that you don’t need to declare types. that was 15 years ago. Now, I prefer the handrails
you spend more time reading code than writing code
much more, even
I don't
I have used enough python to know that I never want loose typing ever again. Keep var the hell away from me
christ, I would not want to write a game without static typing
Although I would not say var is in the same boat
absolutely, var should never be used
It's exactly the same static typing that you get from an explicit type.
it's not dynamic
it’s ok in Python when learning, and you don’t know much. then it’s time to move on to more controlled typing
which does punt type-checking to runtime
except your code is less readable, not a good thing
You look at a function in Python and you have to go through a call stack like eight functions deep until you find the function that originally set the variable to determine it's type
or
You look at the type in the parameter line of the function
Option B seems much better
Down with var
agreed
#varisoverparty
but this has nothing to do with what you just said..
you're describing a lack of static types
that is literally the issue that var causes
I know I'm just traumatized by python
var is only legal when declaring a local variable
how do i get a variable from another game object
like how do i get the run speed from another script
use GetComponent to get a reference to the component with the variable. Then you have a reference to the thing with the variable
well, then you'd need a reference to the game object :p
🐢 all the way ⬇️
we’ll cross that bridge if he asks
anyway, I would not teach beginners about var, at all
!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.
they have enough to learn, without having to learn something that will actively screw them over
public GameObject statsManager = GetComponent<ScriptableObject>();
sth like this..?
im dum]
#💻┃code-beginner message read this.
btw is there a simple plugin to get keyboard input for a string?