#💻┃code-beginner
1 messages · Page 145 of 1
like there is a velocity on the x axis but its like 0.6, and i cant seem to see the body moving
it moves fine when im not on the ground though
Might want to provide more details. Start from a video of the issue.
As well as the relevant code.
i cant record but i can show you my code
i might just rewrite my code lol
are there any resources about platformer movements but instead of jumping, its jetpacks ?
you can simply just change your jump code to add acceleration instead of force when you jump, and change the getkeydown to getkey
Hello, I need some advice, I´m doing a 2D game and Im not sure if I should create the objects when I need them or should I create them when loading the game, and later on set them active or not, for example, I have an enemy pool where I have all the enemies but I don´t know if that would work for when the turrets shoot , does the performance of the game may variate if I create them or if I just set them acrive or not?
does the performance of the game may variate if I create them or if I just set them acrive or not?
Yeah, Instantiating is somewhat expensive, that's why you usually use Pools for things you need to instantiate and destroy a lot: https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
https://learn.unity.com/tutorial/introduction-to-object-pooling#
Thanks, I have the pool system done, but I made It following a tutorial and don´t know how to update it for each Tower, I will read the docs and lets see if I can make it
ty 
Is it possible for me to loop a coroutine until a certain condition has been met?
Yes, that is the most common use for coroutines
ohh lol
Anyone
Where's the question?
I’ll repost
You didn't really describe what your issue even is
you didnt ask a question you just said you were making it
what do you need help with
is there a better way to check if hte player is on ground reliably? im using this and idk if i just suck at values or smthn but its like not working properly, what is ground is a layer mask btw
Oh my bad I need help with making it
well, what have you tried?
Are you using 2D or 3D physics?
Nothing I am not quite sure how to make it
This will only detect 3D colliders
3d physics
I would raise the raycast's origin a bit
I believe raycasts ignore colliders that they start inside of
k, ill try that out, thanks
hi i have a question. Why is my NavMeshSurface not working?
ive been trying to do Monster AI lately
what does "not working" mean?
idk
then how am I supposed to help you?
show me the inspector for your NavMeshSurface component
Also unfold the "Object Collection" and "Advanced" sections
i forgot those were collapsed by default
also, can you share that in #🤖┃ai-navigation ? that'll be a more relevant place
yea
for some reason chaning my collider to capsule seamed to help aswell as doing what you said
thanks for the help! works perfect now
How do I loop a coroutine until a certain condition is met
while loop?
I know it has something to do with that, but I dont know where to place the while loop
and should the while loop be activating the coroutine or the code while it is inside the coroutine
if you want to make a coroutine repeatedly do something until a condition is met, put a while loop in the coroutine
If you want to run the loop once per frame, then you must yield return null; somewhere in the loop
IEnumerator SomeRoutine()
{
while (SomeCondition)
{
yield return null;
}
//condition done
}```
Or WaitUntil https://docs.unity3d.com/ScriptReference/WaitUntil.html
Seems to satisfy his needs too.
WaitUntil is ideal if you just want to...wait, yeah
ok so in theory it should just do the while loop till the condition is true
if you want inverse use ! then or use WaitUntil like suggested
I was already doing this but it bugged out but it fixed itself for some reason
Thanks for the help
what "bugged out"?
The loop ended and the coroutine just ended itself even though the condition wasnt met
while terminates once the expression evaluates to false
Yes
sounds like the Monobehaviour which started the Coroutine was Destroyed
The debug said it was done (Which happens when the while loop is finished) so i'm not sure
ill just see if it still happens
I seemed to have fixed it
Oh wait
I just recalled
ok I know what's causing the problem
how can i find the fuelbar gameobject which has a tag FuelBar?
FindGameObject with tag returns GameObject
so how do we get a component from gameobject ?
i think i know
wait lemme try rq
btw the FuelBar variable is a script right
ik its my code but im not really sure
or a class rather
sure u can make it two lines
looks fine
alright ty
FindObjectOfType can prob be used since it finds the component directly
The scene starts when the variable checked is on 12 for about 45 seconds, and the loop checks every 10 seconds which causes it to stop
I fixed it by adding an extra condition for it to be 12 using ||
the condition is if its less than 6
instead of what
Just to make sure: is there a reason you cannot just make fuelBar serialized or public and just drag the object in
because its for a prefab script and i have to drag n drop it every time
instead FindGameObjectWithTag
idk which one is faster, but I dont use not to use tags so don't take my word on it 🙂 tag should be fine though
Okay just wanted to make sure
A find in start for a prefab is fine
i mean its not like im putting hundreds of them but i just wanna have the smallest amount of things to worry about
how dont u use tags
I use components directly
its like a tag but better since you're not bound to strings 🙂
If there's only one FuelBar object in the scene though you should use FindObjectOfType instead of getting the object and getcomponent, it's slightly faster
yeah there is
All Finds can be avoided with proper planning and dependency passing. The object spawning the prefab could set the variable on the instance after spawning one, for example.
it works now thank you
sweet
i have another question, can i use a foreach loop in unity?
ofc lol
i was asking cuz i tried to use a while loop and unity crashed
the only thing unity can't do is run .NET7+ functions
that will happen if you have infinite loop
regardless
oh alright
while (3<8)
{
//infinite loop crash
}
vs
i = 0;
while (i<8)
{
i++;
//fixed
}```
i know what infinite loops are lol
just checking
If a Coroutine is Started can it be started again mid coroutine?
hmm if you store it a variable you can stop and start again
each time you StartCoroutine you create a new one
Im asking so incase the player triggers a coroutine that they cant just spam it
you can also put a bool
so I false it at the start and true it at the end?
yeah or opposite, as long as you use that to check before startcoroutine
void method()
{
if (running) return;
StartCoroutine(SomeRoutine());
}
IEnumerator SomeRoutine()
{
running = true;
while (stuff)
{
yield return null;
}
running = false;
}```
I honestly don't understand why you don't use WaitUntil, it can't give you an endless loop, it's easier to read, it's less amount of code.
how can I create a parent object for both text and button at the same time
I would appreciate any kind of help
I'm beginner
whats the usecase
what are you trying to do with that
here is the thing, in the tutorial that I'm watching the guy has a parent object called ``game over screen` for both the text and button. Unfortunately, for some reasons that I dont remember, I dont have that one, now im trying to add it
"Create Empty"
but I want it to be parent object
just make a gameobject in hirerchy
so dragthem onto it when u make new empty
so i should first make a child object under the canvas
you can also right click one of them and Create empty parent
What does the return do
and make the text and the button the childs of the child of the canvas?
Just store the coroutine in a variable, then check if the variable is null. If so, the coroutine is not running . . .
returns out of a function
yeah right click on the canvas and do Create Empty and then drag your stuff inside that new empty gameobject
they already are child of canvas
what does that mean
Thanks
ah I get it now
why not just use a regular if statement instead of returning if its not true
"early return" can simplify functions
public void ReticulateSplines() {
if (!ready)
return;
if (!splines.AskToReticulate())
return;
splines.DoReticulation();
}
you just quit the function early
I mean instead of this it's
if(running)
{
Startcoroutine(c());
}
you would need if(!running) Startcoroutine
in this case it's not a huge difference
and I would probably use an if statement at that point
Forgot
You don't need a bool at though, just check the coroutine variable instead . . .
How
StartCoroutine returns a Coroutine object
So it blocks the Statement from happening by returning out of the function?
Store the coroutine when you call StartCoroutine. Then check if the variable is null . . .
it "returns" early so it doesnt execute the rest, it doesnt block anything, code runs top to bottom
I wouldn't say it blocks anything, yes. It just stops early.
// setup
var coroutine = StartCoroutine(SomeMethod);
// checking
if (coroutine != null) { return; }
How does it return as null
When the coroutine is not assigned. Inside of your coroutine method, at the end, assign the variable to null . . .
Thanks
can someone tell me what is wrong with this code?
its nested inside Update
thefore cannot use accessors
That means the coroutine variable should be a field (class-level variable) . . .
how can I do that?
The curly bracket is in between update too
Move it out of update
pay attention to the brackets
if you formatted your code properly you would see the problem
Your method is inside of another method; this is called a local function (method). When doing this, you cannot use an accessor for the local function . . .
I have a problem where in my script function "PromjenaDepositZnakova" return true and the if statement doesnt run, it is true for 3 frames, so i thoth that was the problem then i used second variable that makes the "If" staement active until it is finish with the desiered actions but it didn't help, any ideas becouse i have no clue?
nvm That's for a method woops
I understand, thank you guys
Please configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
What will that do?
you code better and get you help here
its also part of the community rules here to get help
Shows you errors
ok
No, configure your editor first, it's pointless to help before that.
they said it shows you errors
also please learn about arrays, whenever you start using numbering on variables you definitely need a collection
they didn't ask to show the current errors
My bad
oh
Also, Random.Range(0,1) aint gonna do a great deal
also that Random.Range only return 0
(intiger version is max exclusive if you want 1, you always need +1)
Random.Range(0,2) // this gives 0 or 1
That was me just testing something and messing around with values, later that random will be from 0 to 6 but the real issue is the If argument doesnt react to getting true from the function, ive configureded IDE.
Do not use deltaTime with mouse input
you're getting a distance, not a velocity
so multiplying by deltaTime is incorrect
You'll need to adjust your sensitivity down a fair bit
It's a common mistake to make
You'll want to think about whether you have a distance (mouse input) or a velocity (joystick or keyboard input). If you have a velocity, use deltaTime to turn that into a distance.
and similarly...
float gravity = -9.81f; // acceleration
velocity += gravity * Time.deltaTime * Vector3.down; // velocity
transform.position += velocity * Time.deltaTime; // position
show the entire screen so we can see what ur actually trying to move
not really a code question here
also are you using colliders for UI ? 🤔
ohh i saw green box thought it was collider
idk that size looks extremly large for that box for text
you should learn proper anchoring
this goes in #📲┃ui-ux though
Yes -- check the docs in there
You should take a little time to read how RectTransforms work. It'll make your life a lot easier
I just kind of stumbled around blindly for a while before I actually read how stuff works
that was as error
Although, other than mouse input, I can't think of any common cases that get messed up
so that's most of what you need!
You're in play mode. Do you have code setting its position
You can't move something while code is setting its position -- it'll just move back to where it was
Could someone help me with the ide of VSC?
!ide
Oh the bot is broken
Here, try this link
#💻┃code-beginner message
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
VSC is difficult to get setup properly. If following the tutorial doesn't help, you're in uncharted territory. Try to redo it, make sure everything is closed beforehand, restart the computer, open Unity, double-click a script file to open up in VSC and hope it works . . .
or, better yet, just use VS
it does work also did you get the .NET sdk
yeah
try Regen Project files
i get an error that says something about a microsoft error
show error
WAIT WTH
It works now
the error dissapeared
and i had the error for like 2 days straight
That reminds me, I need to install and start using Rider. It's wasting away . . .
u got it free?
i had this error
weird
Heavily discounted for under $50 sometime last year . . .
ohh that aint too bad.. could be great alternative once VS is removed for mac in august . I hate vscode
how do i access surface inputs in code?
whats that ? shader?
yeah
I mainly use vscode bcuz visual studio was bloaty and loaded slow, and luckily, didn't have issues with it breaking
Now it breaks connection often, Unity stopped supporting it, and Rider with co-pilot is ridiculous. The switch is warranted . . .
Get function in the material should work iirc
Yeah the new plugin is much better for VScode then the process for before but the intellisense kinda sucks and i still hate the same line formatting (it only formats proper new line for me after i hit save)
im on mac soo and m$ is stopping vs mac support in august so i either go full on VScode or use rider
The Material class has lots of methods for getting and setting properties
e.g. GetFloat/SetFloat
Note that you need to use the actual name of the property. The name you see in the inspector is generally different.
Who knows? Maybe the Documentation does
One way to find out is to right-click on the shader dropdown and click "Select Shader"
so _BaseColor is the correct name to use if I want to adjust the property named BaseColor in the inspector
Oh snap, that sucks. They're forcing your hand . . .
Unfortunately im back with another issue
using System.Collections.Generic;
using UnityEngine;
public class X : MonoBehaviour
{
public bool Turtle;
public GameObject Bar;
void Update(){
if (Input.GetMouseButtonDown(0))
{
//cast ray from mouse position
Vector2 clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(clickPosition, Vector2.0);
}
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);
if (hit.collider != null && hit.collider.gameObject.CompareTag("X"));
{
Turtle = !Turtle;
Bar.SetActive(Turtle);
}
}
}
getting some errors with that
Assets\X.cs(18,72): error CS1003: Syntax error, ',' expected
seems like the error says a comma is missing on lines 18 and 72
inside the code there are two things underlined in red. Vector2.0 and hit all on the same line
line 72?
it only goes up to 39
Column 72 . . .
what is a Vector2.0? theres no such thing
u mean Vector2.zero probably
I'm not sure, I'm fixing my friend's code since he isnt on rn and I need to fix this
Not sure if Vector2.0 is a thing. Did you check?
yes!!
okay so then there is hit
A local or parameter named 'hit' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
Also, you should show a picture of the error, and point out which line is 18 because there are no line numbers when you don't post a link . . .
ur declaring something called "hit" twice
So I could change the word hit to like frog or smth
Configure your !ide so you see it underlined in red
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it is
if they were in separate methods it would be fine. but in the same method, yeah u gotta change one of them
Okay, so do you see the red underline on the line with the error
Haha, name it whatever makes most sense for what it's being used for, but yes
So then that combined with the error should be pretty obvious what the fix is
this dig
well it wasnt
Then you should probably learn some basic C# syntax because this line is obviously incorrect
There's no such thing as Vector2.0
and it works but now says "There are 2 event systems in the scene. Please ensure there is always exactly one event system in the scene" but it works so
great, and where can I learn that?
That'd be because there are 2 event systems in the scene. Please ensure there is always exactly one event system in the scene

Do you want to pause it, or stop the animation completely?
Ik this may be a very stupid question, since am new on doing particles, but how may i make that a particle appear exactly on where i want? (I have a GameObject that is supposed to be the place where it has to spawn)
Who could have thought. Why do I have to change it though if it works
by default it should appear where the gameobject is at
Because it's going to stop working as soon as you try to actually do anything with the event system
So i have to place it as a child?
im working o blocking system in sword combat and as soon as i hit a colider with tag enemy whle blocking i want to stop the animation and play the one that i got blocked
yeah that works
Okay, thank you
I will fix it
later
Just have to have a transition to the "Bounce Back" animation or whatever, and set a trigger for it.
And make sure the transition does not have an Exit Time.
also after setting it to be the child, change its coordinates to 0 0 0 if u want it to go into the center of the parent
Yeah but the object deactivates itself on trigger, are there any other options?
is it a moving object?
Yeah, it's an enemy
but im stupid and dont know which system is extra. i have two weeks to make a game and i dont know c# so im just trying to cobble it together. Im learning c# at the same time
theres something about the particle system that lets you set a source or something, i dont remember exactly
It literally does not matter which one, just delete one
https://docs.unity3d.com/ScriptReference/ParticleSystem.Emit.html this takes a position as a parameter from where u want to emit it from
ty
oh i see one is clickposition and one is mouseposition
...what?
Did you rename them?
No but there are two things and each are the same code but one is click position and one is mouse position
What does that have to do with the extra Event System
Are there two separate game objects named that? And both have identical Event Systems on them?
is that not the second event sytem
no game objects are named clickposition or mouseposition
Have you located the two event systems?
why isnt this working?
event systems are in your hierarchy, not code. its a gameobject called EventSystem
Event System is an object
called Event System
Why would it work?
In what way is it not working
im prety new to the animator im trying to replicate this type of combat (he is using animator to do all this) u have any idea how to do this ?
Layer is an Int
alternatively it could be called something else if it was renamed. in that case click on the gameobject and in the inspector you will see a component called Event System. you should only have one of these in your scene
how can i get the name of a layer? layer.name doesnt work
weird well I ddeleted the game object called Event System
I do not even recall making that\
ever
it gets made automatically when you have something in your scene that requires it. no idea how you got it twice though
what but now I have nothing called that in that section
any suggestions on how to do the aiming mechanic for this?
quick breakdown its a point and click to move type bullet hell game where positioning is a core mechanic (autobattler) you'll end up moving by clicking the unit and drawing a path.. every X amount of mouse movement will trigger a new node/waypoint..
i dont want it aiming at the mouse all the time.. i'd want it to aim the direction its walking.. unless i give input to tell it to aim somewhere else.. (a general direction)
i was thinking like click and drag and release.. to give it a direction..
and since hes moving.. id have like a big buffer zone where u wouldnt need to click exactly on him, just nearby
but.. then once he gets to the next point he'll look the direction hes walking again.. or maybe he wont.. im unsure at this point.. just trying to think out the next system i gotta make
In the Animator window, you can right click on an animation and Make Transition and link it to another anim. In the Parameters, make a new Trigger, call it whatever you want. Click on the line, turn off Has Exit Time in the settings and add the Condition of your new trigger. In code, call animator.SetTrigger("TriggerName") to transition to the new anim.
folow the mouse mby ?
u must have some event system component on one of ur gameobjects which u accidentally added onto it? cuz it said u have 2
That would probably be because a tag is not defined
That makes a variable named ExitButton that can hold a GameObject and has absolutely nothing to do with tags
how do i define it then
First off, what is the exact error you're getting
because it was working before when it was named X and there was no tag define
Tag: X is not defined.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
X:Update () (at Assets/X.cs:26)
Okay, so you have no Tag in the project named X
Add one
so do I just throw GameObject.FindWithTag("ExitButton") at the top
no check my link to see how you can add a tag into your game
okay
ur code is looking for a tag named X so u gotta make a tag named X
How are you going to find a tag you do not have
If you cant figure it out, just use GameObject.Find("yourgameobjectname");
Or: Best solution, don't use Find at all and just drag in the reference
hes using CompareTag
ExitButton = GameObject.FindWithTag("ExitButton");
Instantiate(ExitButtonPrefab, ExitButton.transform.position, ExitButton.transform.rotation) as GameObject;```
I followed the website
it still does not work
did u add an X tag and a ExitButton tag?
I dont need an X tag because Im just trying to deal with ExitButton
u still got that CompareTag(X) tho
but it never mentions X as a tag
Also your if statement contains nothing
using System.Collections.Generic;
using UnityEngine;
public class X : MonoBehaviour
{
public bool Turtle;
public GameObject ExitButton;
public GameObject Bar;
void start()
{
if (ExitButton == null);
ExitButton = GameObject.FindWithTag("ExitButton");
Instantiate(ExitButtonPrefab, ExitButton.transform.position, ExitButton.transform.rotation) as GameObject;
}
void Update(){
if (Input.GetMouseButtonDown(0))
{
//cast ray from mouse position
Vector2 clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D frog = Physics2D.Raycast(clickPosition, Vector2.zero);
}
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);
if (hit.collider != null && hit.collider.gameObject.CompareTag("ExitButton"));
{
Turtle = !Turtle;
Bar.SetActive(Turtle);
}
}
}
ok u renamed the X to ExitButton
yes
So show your ExitButton tag
all u need is to make an ExitButton tag then
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gunny: MonoBehaviour
{
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 10;
void Uptade()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("pressed");
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
}
}
}
!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.
oh mb
Why does it say Uptade?
how do i make a taggggg
ExitButton = GameObject.FindWithTag("ExitButton");
Instantiate(ExitButtonPrefab, ExitButton.transform.position, ExitButton.transform.rotation) as GameObject;
}```
I thought that was making the tag
i said look at my link 😭
why
Thats finding the tag
Not making it
using System.Collections.Generic;
using UnityEngine;
public class gunny: MonoBehaviour
{
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 10;
void Uptade()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("pressed");
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
}
}
}
i didnt scroll down 😭
Where do you call Uptade
Change it from Uptade to Update
wait
okay so
am I supposed to use ExitButton in that or respawn
If you want to find an object with a tag, you need to have an object with that tag
great okay I made a new tag called ExitButton
the new code u added is completely unneccessary and used for something else. it was just an example in the docs. all u need to do is click Add Tag like that image i showed and its done
ok well now everything is broken
this has somehow broken another set of code
im just going to stop for a bit
Honestly this entire script is basically nonsense. You just never realized it because it errored out immediately and never ran any of it
well we can blame my friend for that. I will let him now the script doesnt work
maybe ur friend generated this code with chatgpt
idk how he got it
the point is the raycast method he was trying to use worked for the dragging code he make
The raycasting code makes zero sense.
maybe it can indeed work like Physics2D.OverlapPoint when the direction vector is Vector2.zero?
Let's see:
startwill never be called by Unity for similar reasons that other question we answered won't runUptade- If statement with nothing in it
- Instantiating a prefab that literally does not exist in the code
- The entirety of the first
ifstatement in Update does nothing whatsoever. It spins up a few local variables, does nothing with them, then ends. - Raycast with a direction of 0
- Superfluous boolean (with a very strange name) for toggling
Bar, can just set the object's active state to whatever it isn't
D- see me after class
hi im adding sounds to my game and ive got a audiomanager script https://hatebin.com/mpulbheocp attached to a game object tagged audio manager which doesnt destroy
i then find the object with my player and send a message to use the Play function https://hatebin.com/clevgevhdp
but wether i put this AudioManager = GameObject.FindGameObjectWithTag ("audio"); in start or update it doesnt work
is it tagged 'audio manager' or 'audio'?
just audio
Show the object and its tag
that else if statement is haunting
thanks
AudioManager in your PlayerController is a GameObject. You'll have to get the AudioManagement component, will you not?
This whole setup is haunting tbh
ive tried that too
Putting this in Update omg
but that also doesnt woek
Who needs to reference the component and call methods on it when you can just use a dirty method like SendMessage and not even care about whether you're referring to the correct type of object
i tried it in start and it didnt work testing :/
Jesus christ how horrifying
it doesnt work because ur not calling it from the instancea nvm ur just not Getting the Component from GameoObject
ive tried that tooo but we got taught to use send message]
the rest of my code uses references promise
Slap whoever said that
No cop would convict you
teacher :p
bad teacher
fr
I don't think I have ever typed the words SendMessage before in my life
a sane person would at least learn events since thats what its trying to mimick
SendMessage is an ancient solution to a problem that existed fifteen years ago and should have been removed when they removed .collider and the like
I would only use SendMessage if I genuinely needed to trigger a method on a completely arbitrary component
im using Unity 2018.2 and Monodevelop
with no ability to specify the signature of the method ahead of time
Anyway, we've dogged on the setup, what are people's recommendations for a rework here?
i'm developing some Opinions over here
just calling the method on the reference should be sufficent
- Change the AudioManager reference to an actual component reference
- Drag in from the inspector if possible, if not at least use the Find once, in start
- Call the
Playfunction directly instead of through send message
If you need to call Bar, a method that's part of a class named Foo, you should get a reference to the object and call the method directly.
[SerializeField] Foo myFoo;
void DoSomething() {
myFoo.Bar();
}
Hi I'm not sure wher eto ask about this issue, but I just created a new URP project and after I select the camera it stops rendering anything... does anyone know how to fix this? https://i.gyazo.com/eeb3bb31290ccb04a014ff367bc35c54.gif
where da code question ?
Like I said I'm not sure where to ask this
#💻┃unity-talk for anything else
also would show the inspector more
Ok thanks I'll ask there
this ensures that you actually have a reference to a Foo, not just some random object
and it's a lot more efficient to call a method instead of using SendMessage
Unity has to go rooting around in the guts of the target to see if a method with the appropriate name exists
Or be incredibly lazy like me and learn Singletons and abuse them so badly but never let anyone look at my code
Singletons get unnecessary bad rep
will finding the component through start work if it is on Dontdestroyonload
or should i just put it on each scene
not if they're not both in DDOL
every good game has dozens of singletons
you can use a singleton though
I forget how the Find methods work with multiple scenes
iirc they do not last I tested
If the "Audio Management" component is getting punted to another scene, then I think it's very reasonable to just make it a singleton
"B-b-but my DI!!"
hot take: singletons are dependency injection
why not both
your object gets its value from somewhere else
Or the other one people say, mock testing
time to mock out the final boss from my game so i can test...something
to explain what we mean by this "singleton" business
a singleton is something that exists exactly once
If you have many copies of something, you can't just say "give me X" and get the exact instance you wanted
if there are 10 enemies, you can't just...pick one at random to deal damage to
But when there's exactly one instance of something, you can always get exactly the instance you wanted
The easiest way to make a singleton is to do something like this
public class AudioSystem : MonoBehaviour {
public static AudioSystem instance;
void Awake() {
instance = this;
}
}
you can now reference the audio system from anywhere as AudioSystem.instance
(not in other Awake methods, since they might run before the AudioSystem's Awake does)
This is not the best way to do it for a few reasons (the timing issue, nothing stops you from making multiple instances by mistake..)
But I think it's very serviceable here.
Before you make something a singleton, you must ask yourself if it's truly only ever going to exist once.
Oftentimes, singletons will be "manager" types
look at my cute little managers
I access my other managers by 1 main manager so I just make that the singleton and grab the rest with props,
imo no need to make 20 diff managers singletons
That's also a good idea
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}
Just to keep things clean
I have one true god-manager -- the GameController -- that lives forever and keeps track of high level game state
and then I have others that only survive for a single scene
(hence why "Game" is a bad label...it's not called that anymore. i should change that)
it's the Encounter Manager now. it handles a single encounter in the game
i'm having animation nightmares today and I still have a cold, so I'm taking it easy lol
do u call Manager.Instance a lot of times from other scripts without caching it or do you cache it into a variable in each of your scripts?
I prefer not to cache when it's such a tiny thing, personally
no need the instance is pretty much a prop so
yea
If I have a loop that runs 20,000 times per frame, I store the value I got from a dict instead of reading it thrice
Although, it can be hard to tell how important those tiny function calls actually are.
Deep Profile adds a huge amount of overhead to each function call, so lots of tiny calls get blown out of proportion
(I did still see a minor gain in regular profiling in that case)
Debug.Assert becomes super expensive in deep profiling
especially if you have a formatted/concatenated string message
Debugging or writing is always expensive, concating strings is also a bit of allocations
using UnityEngine;
public class Bullet : MonoBehaviour
{
public GameObject impactEffect;
public float life = 3;
void Awake()
{
Destroy(gameObject, life);
}
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "enemy")
{
Destroy(collision.gameObject);
GameObject ImpactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(ImpactGO, 2f);
}
Destroy(gameObject);
}
}
Hello, i am new at unity and i need help with sharing variable between 2 scripts my first script has a correct value of 2 and my second script has a value of 0 that's probably because the value cannot be shared to the other script.
Is there any way I can fix it?
how can i change this hit to like collide or something bcs i copied it from raycast thing
Hey, guys! I have a question. How to don't give permission to the player to interact with any button before the game starts, for example I want to make a functionality that the player enters the main scene of the game and when it enters then to give the permission to the player to interact?
A boolean and some if statements
See what functions you have available to you in the Collision class
https://docs.unity3d.com/ScriptReference/Collision.html
!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 have already the functionality of the player movement. What I want is to make that happen. I will show you my player movement code now give me a minute.
{
if (Input.GetKeyDown(KeyCode.Space) && uiManager.pauseIsActive == false)
{
playerRb.AddForce(Vector3.up * jumpForce, ForceMode2D.Impulse);
audioManager.PlayerJumpSound();
Debug.Log("We give force to the player!");
}
else if (Input.GetKeyDown(KeyCode.Space) && uiManager.pauseIsActive == true)
{
audioManager.jumpSoundAudioSource.Stop();
}
}```
I am giving force to the player with a space button here!
If you don't want the player to move before the game starts, but the object exists anyway, use an if statement to only run your code when you're supposed to
Collisions have contact points. You can access the first one using collision.GetContact(0), then access its .point and .normal properties
I didn't clarify that correctly I just want it to happen at the period when the player start moving at players position which is behind the main scene to the starting point position where the game actually starts and the player can interact with the buttons and all.
If you want some condition to be true before accepting input, wrap the input in an if statement
!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.
that doesn't work for me
Yes it does
does this code look fine cuz it doesnt work but i dont see anything wrong with it
whenever the player collects a battery the battery is SetActive(false)
and the tag name is right
Find methods don't find inactive objects
If works but it doesn't do anything. The objects are already active so activating them again won't matter.
will it activate the ones that arent active?
No because Find doesn't find inactive objects
ohhh
Returns one active GameObject tagged tag
what if i make that array at the start of the game?
when all the batteries are active
will it store them even when they are inactive
Yes that is an option
!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.
can you explain pls
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Open one of the websites. Paste the code. Click the "Save" button.
The URL will be replaced with a link to the paste, copy and paste it here
Put the code on a paste site.
Put the URL here
you're supposed to share the URL, not paste it to the site then download it and upload it to discord
I'm trying to figure out the best way hypothetically to effectively store lines for a game in an organised and expandable way.
I discovered json, which seems like a pretty solid way to do it, but because this requires an object type to be defined to be serialised to, I don't think this would be the ideal use case for it as I don't want to make a new object for every line.
why not use 1 type.. with as many ever properties as you need?
A JSON file can contain an array of strings just fine, and you'd only need one class
https://hastebin.com/share/duremowage.csharp and https://hastebin.com/share/oligicisek.csharp I don't know why the 'level' is not the same for both can sommme wan exsplane what is wrong
Eeach script has their own variable named level
They have nothing to do with each other
theye are conected by the [SerializeField] public StarterTexstScript starterTexstScript; and [SerializeField] public Doorscript doorscript;
That has nothing to do with level
You have a reference to the other script but you aren't using it anywhere
You are just using this script's level variable
how do I fix it than Idk what I can do about that ?
If you want to use the level variable from the different script, get it from your reference to that script
yes but how ?
With .
what I don't get it
theOtherScript.level =
if you just say level = your basically saying this.level = which is the level within that class
someReference.variableYouWantToUse
like dis ? : Doorscript.level

but there is a red line under it
you use the name you gave it
And what does it say
[SerializeField] public Doorscript.level;
negative
No
br pls I don't know
Use the level variable from your Doorscript in code
Do not have a variable level on this script
public DoorScript doorscript;
doorscript.level
you have 2 different levels in ur scripts.. one belongs to one script the other belongs to the other script..
if ur in one script and you want to access the level in the other script.. you have to use the variable OF that script..
but WITH the name
that is in my script
So use that
so if (doorscript.level == 2){}
[SerializeField] <-- asks Unity to store this field, even if it isn't public
public <-- allow anyone to see the field
Doorscript <-- this field holds a "Doorscript" object
doorscript <-- the name of the field
the name of the field is the only part you need to write to access the field.
this will use the "level" variable of the script that you declared as "doorscript"
makes sense to me
but it doesn't work
the eror is :
'Doorscript.level' is inaccessible due to its protection level
private means the variable can only be used inside the class it's defined in
protection level.. thats the public, private, static part u put before the type u declared
the level isn't the same in the to scripts
well, it sounds more like the code doesn't even compile
yhea I know
public means u can access it anywhere.. private means you can only access it in the script that it sits in, and static isnt important right now..
well..
If you know then why did you post your error here instead of just fixing it
u can't access a private variable from an external script..
you need to use a public variable.. if u want to access it from other places..
i dont think he's using his brain.. other than fishing for exact solutions
I don't know what is ronge but I am gane restart my pc so bey I tink i fix it btw
restarting your computer will not fix your code.
it works sorry there was a other mistake sry bey

🍀
"it works now, sorry. there was another mistake, sorry bye"
oh i could parse the sentence
lol i almost couldnt
I couldn't
i was just pondering the situation as a whole
variables..
complicated stuff
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
gameIsPaused = !gameIsPaused;
PauseGame();
}
}
void PauseGame()
{
if(gameIsPaused)
{
Time.timeScale = 0f;
pauseNotif.SetActive(true);
}
else
{
Time.timeScale = 1;
pauseNotif.SetActive(false);
}
}``` i thought when you set timeScale to 0 the update stops
guess thats not teh case
no, update is still called. but deltaTime will be 0
ahh so its fixedupdate
ya, i just had em mixed up
thats great news tho, i was thinking id have to do something complicated to achieve a pause
This can also happen when you start the Recorder
that caused some funny problems for me (division by zero)
I may be stupid but I'm at a loss. Trying to read this simple array from a file is so far doing nothing...
That class does not match your data
Your data contains a single object. The object has one name -- "Scene" -- and one value -- an array of strings
Your Scene class has a single array of strings named "Lines"
These do not match at all.
- Don't name this
Scene, that's a Unity class, you should use unique names - Create one manually using
ToJsonso you can see the format, then you can edit it outside of Unity to change it
Each field on your class will become a name in an object. So you'd better have "Lines" somewhere in your JSON!
^ and yep, just produce an example to look at
Aeugh. I haven't used JSON since modding minecraft years ago and it shows
I will produce an example then!
Hey guys, I was trying to see if theres a simple way to find the total length of a slerp curve, as in, vector3.distance between 2 points, however while accounting for a third midpoint somewhere. I did find the following solution:
Vector3 previousSample = A;
float distance = 0;
for (int i=1; i<sampleCount; i++) {
Vector3 sample = Vector3.Slerp(A, B, (float)i/(float)sampleCount );
distance += Vector3.Distance(sample, previousSample);
previousSample = sample;
}```
but it seems rather crude and I was wondering if theres a simpler/mathematically perfect solution out there?
Well assuming your vectors are both the same length it's a simple matter of taking the angle difference as a portion of the circle circumference
you mean as in the distance from the midpoint? see they might not always be the same is the problem :/
No. I mean distance around the circumference of the circle
It's odd to be doing slerp between non-unit vectors
It's non-trivial for two differently sized spheres
It's pretty reasonable!
I've used it for moving a look target from place to place
I would think you just take the average of the two circumferences if they're not the same length
(well, I really did a cylindrical lerp, but that's just XZ slerp + Y lerp)
I think I looked into this before. I didn't get a good answer.
You can approximate it by just sampling a bunch of points, of course. Looks like that's what you did.
what would this error mean? this is the script
it doesnt give me any errors in my ide
hey guys, I have an animation that rotates an object clockwise by 360 degrees forever (in case you ask, yes, I need an animation because then I can take advantage of animation speed). In a given moment I need to stop the animation at whichever rotation the object is and make it return to its original rotation (0, 0, 0) in exactly 2.25 seconds. any idea about how to achieve this?
Read through the "Troubleshooting" links on that page.
probably calling this method before the singleton instance has been created
I think I know what you mean, basically just take the angle difference from the midpoint to the start/end point, then just do 2pir*angle/360, with r being the average distance between the start/end point and the midpoint, and with "angle" just being the angle I found earlier?
The average radius is probably an okay approximation
why exactly do you need an animation for this instead of just using something like Transform.Rotate and a scale value?
because of animator.speed
If you want to be able to vary the speed, just...change the amount you rotate by
again, scale value for controlling the speed
It means something on that line is null but you're trying to do something with it anyway
You could control the speed of the rotation in code
in fact, you would have more control over the speed if you do it via code
so that something is _optionsData.masterVolume right?
it could be that, or it could be your singleton instance
idk what that means
It could either be AudioManager.Instance or _optionsData
if it was audiomanager instance wouldnt the next lines of code give an error too?
why would they? you never reach them in the first place
it wouldn't reach the next line of code
How would it reach those lines, it's already died
oh
Runtime errors aren't going to show up in your code editor.
You'll see errors in your IDE when there's something provably wrong with your code
int x = 3.5f;
this is a compile error because you can't assign a float into an int variable
var foo = GameObject.Find("What");
foo.name = "Hi!";
This will throw an exception unless there happens to be a game object named "What" in your scene. The compiler can't prove that, though. Everything is structured perfectly correctly.
Figured out how to serialize and de-serialize JSON properly for strings and integers, but noticed this in the documentation:
Unity does not support passing other types directly to the API, such as primitive types or arrays. If you need to convert those, wrap them in a class or struct of some sort.
I'm not quite sure what it means by 'wrap them in a class.'
alright so i think i found my error, that applyalloptions method is called in a Load method and that Load method is called in Awake
could that be it?
because awake is before the first frame so the audiomanager doesnt exist yet
string[] myStrings; // can't serialize this
MyClass myStuff; // can serialize this
where MyClass is
[System.Serializable]
public class MyClass {
public string[] strings;
}
The corresponding JSON would be
["a", "b", "c"]
and
{ "strings": ["a", "b", "c"] }
respectively
Oh wow, thank you! That's exactly what I needed to know
well, you can probably get the time between the start and end keyframes and normalize them values. Then from the point from where you stopped, you need to figure out the speed needed to get back to 0.
this is a code channel
I was wondering if you can add a script
To block a animation
this sounds a lot harder than being able to just do...
[SerializeField] float spinRate;
private float returnRate;
private bool spinning = true;
void Update() {
if (spinning)
transform.Rotate(0, Time.deltaTime * spinRate, 0);
else
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.identity, returnRate * Time.deltaTime);
}
public void Return(float duration) {
spinning = false;
returnRate = Quaternion.Angle(transform.rotation, Quaternion.identity) / duration;
}
that'd do the trick!
could this be it?
yeah if you just wanna do it without the animator
oj my bad
but if the clip is just a rotation then yeah use rotational methods
Trying to add a countdown timer to the start of my game but when I press E (the key to activate it), it just goes on to 3 and stops there.
There we go, I can work with this now. Tysm for the help!!
If you want to do more complex serialization (like serialization of dictionaries), consider Json.NET
Is the object this script is on ever disabled or destroyed
It's on the UI object, which is enabled at the start
I didn't ask what it was at the start, I said ever
A deactivated or destroyed object ends all coroutines
Some of the objects parented to UI get disabled, as part of the countdown process
but other than that, that's pretty much it
Is this object ever destroyed or disabled
No
the one the coroutine is running on
Have you changed the TimeScale
Timescale affects WaitForSeconds
Ah
Anyone can help? I want to create bullet holes on wall and i having these flickering images.
I made a Quad, inside a new gameobject with sprite renderer and i attached my bullet hole. Made a material for it then prefabed it.
Code im using:
if (hit.collider.CompareTag("wall"))
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal * 0.025f));
}
Is there another way to pause everything without affecting WaitForSeconds?
Learn how to pause your game in Unity in less than 2 minutes without setting timescale using events.
This allows you to still use time-based logic in pause menus and background systems and can even be extended to work for cutscenes, loading screens and game over screens.
TIMESTAMPS
00:00 Intro
00:05 Game State Manager
00:51 Hook up Player Move...
Check the documentation:
https://docs.unity3d.com/ScriptReference/Transform.html
There are many methods and functions at your disposal
you could use WaitForSecondsRealtime, but for a better pause system you should check the video linked here
are you using URP just use decal projector instead of quads
one note: there's no point to multiplying hit.normal by anything
FromToRotation just goes between two directions.
Did you want to offset the bullet hole from the wall? You need to add hit.normal to the position you spawn at.
Yes, URP but i can't find where could i enable decals, also i using multiplying so the hole wont appear on the surface of the wall to prevent flickering but it not works.
That worked fine dor me 👍
its a Renderer feature
https://youtu.be/P4HwA-O9vB4?t=21
Im trying to make a disjointed hitbox to detect ground collisions, but it dosen't seem to be working. What could i be doing wrong? `{
public GoblinMoves myGoblinMoves;
public GameObject myGoblin;
public float yValue;
private void Update()
{
yValue = (float)(myGoblin.transform.position.y - 0.03);
transform.position = new Vector3(myGoblin.transform.position.x, yValue);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
myGoblinMoves.jumpSpeed = myGoblinMoves.jumpSpeedControl;
myGoblinMoves.jumpCount = 0;
Debug.Log("Detected Collision");
}
}
}`
to clarify i get no collisions
Log the object you hit outside the if statement
see if you're colliding with anything at all and if that thing is the object you expect it to be
I tried that but i have 3 option that (performant, high fidelity and balanced)
well you can pick which graphics settings you want to add it to
and where can i see which one the project use?
Edit > Project Settings > Graphics
Hey there, does anyone here have any experience with the System.Diagostics.Stopwatch? Is it more accurate than Coroutines or timers in an Update loop?
apparently not
The Three Commandments of OnCollisionEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 2D Rigidbody on at least one of them
thank you, i was adding this to balanced and it use high fidelity. i will try mess around with it now
It's more suitable for performance measures
does it matter if i put the component on the tilemap for the hitbox gameObject?
also whats the easiest way to disable physics
Oh alright thanks!
So is there any way to accurately check for milliseconds
Since coroutines and normal timers don't seem to be millisecond accurate
why do you need ms accurate methods?
hi can i ask for some help?
anything you do in unity will be happening on a frame, so you can can accurately mesaure time but your code will all be executing on frames
I'm making a game where you have a couple of invincibility frames if you get hit and use a coroutine for it. The difference in time is always a bit different though, and I would want it to be as accurate as possible since it's a precise platformer game
sure
im having some problems with a ray not apearing in the scene i dont know what to do
So what's wrong with using frames
You physically cannot interact with anything between frames
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
so it really doesn't matter if your timer is up on a frame or between them
📃 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.
📃 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.
ur supposed to like read the massage bruh
question, is it possible to run the game window at one frame intervals?
Yes, that's what the button next to pause does, it advances exactly one frame
oh okay
you mean set custom fps? nvm
Run the game, pause it, and you can frame-by-frame with the third button
True, but how would I use something like WaitForXAmountOfFrames?
well my bullet holes are worse now thru decals
how so ?
´´´cs
Just use a normal timer, the most it can be off by is one frame.
just use a bin site, mate
weird I dont get Zclip. Try moving it slightly outward from normal
I have to go, will be back in a hour. but thank for the help so far
im not really understanding how to use the sites
a powerful website for storing and sharing text and code snippets. completely free and open source.
lord..
sorry
Okay, good. Now what is the actual question
so is Gizmos enabled ? and are u sure script is running?
It’s more consistent to use a timer in sec, unless you want to offset some process by exactly 1-2 frames.
Coroutines are good to delay something by some amount of time and/or frames.
yes the script is running and i saw the ray line but somehow it stoped working when i switched to private the (public camera cam)
Does this object have a Camera component on it
so you have errors in console?
yes
no
Show the inspector of it
tisk tisk
main camera?
you see what you're doing here?
cam = GetComponent<Camera>();
So the code is doing exactly what you asked
You only draw the ray if this object has a Camera component on it
since it doesn't have one, you don't draw the ray
but the camera is set as child on the object
You aren't checking any children
do i drag it in?
then you have to remove the GetComponent if you do
GetComponent will override the inspector, always
you had it assigned but at runtime it was null
is there a default circle outline sprite in unity?
so its working?
oh great
the red ray is what i wanted to see and was working before, but when i press play i have to select the camera on inspector, i didnt figure out to to put the camera in the inspector from the hierarchy
did you not read the previous messages?
it's because you were overwriting the already assigned camera with your GetComponent call
Because I've been sitting here for a while pondering this, I'm wondering if there's a better way to do it.
I want some dialogue to trigger a delay, so there's a few seconds of nothing before another line pops up. The way I was going to implement this was have some lines in the text file simply say "t=5", and when I read the dialogue, these get omitted and a separate list tracks when the current line index matches this delay index, and waits.
Does Unity have any built-in systems to handle events like this that would be less crude and easier to edit?
No, you either make it yourself, or you use very well done assets like Text Animator off the store.
yes thanks for the help
i did it its working
Hi, my project is on unity vers 2021.3.18f1, I have the input system version 1.4.4 but I need 1.7 for a certain feature. How can I get 1.7 in my project instead?
update it?
package manager
Alright. I think I'll step back and make a proper event scheudling system for my games instead of continuing this hacky one, then
it wont give me that option it says "up to date"
Sounds good, thanks
hmm maybe because im on 2022
doc says 2019+
yeah I checked, its got me confused, I dont know if there is maybe a git url install or something?
works fine 2021 just checked
maybe remove it and try adding again
did you add via git or something?
Remove and try adding it from the Unity Registry in PM
Yeah i just did that still stuck on 2022s 1.4.4
I dont need to have the 2023 version of the editor installed to have the 2023 vers of these features right?
no I just showed you works fine on 2021
something wrong with your package manager or something
this should be in #💻┃unity-talk tho
ok
is it possible to have something like the SpriteRender.enabled = false be applied to children as well>
Sure - loop over all the renderers and disable them in a loop
e.g.
foreach (Renderer r in GetComponentsInChildren<Renderer>()) r.enabled = false;```
oh thanks
how do i make it so when the player gets close to grapple point the grapple disables and they get "launched" from the grapple like when they swing off instead of the current dead stop
Is there a proper way to code and comment? I was reviewing my code and realized that not only is it messy, but sometimes I'm rarely commenting and sometimes I have comments on every/every other line
It makes sense to me but I feel like it will make it difficult for others to read
hi i need help
Enemy Code:
using UnityEngine.SceneManagement;
public class EnemyController : MonoBehaviour
{
public float health = 100f;
// Function to apply damage to the enemy
void Update()
{
if (health <= 0)
{
Die();
}
}
void Die()
{
Debug.Log("Enemy died!");
// Additional logic for enemy death can be added here
Destroy(gameObject);
}
}```
**Gun Code:**
The bullets don't hit the enemy, what to do?
!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.
ok
How are they supposed to hit the enemy? Not gonna download a file, but if it's physics messages, look here
Edit: wrong link, one sec
https://hastebin.com/share/edoqocoguc.csharp does anyone can help me solve this .. basically this code to collect calorie and stone .. i want to save only stone and appear in other scene .. but only Stone1 appear... and if i put 3 or 4 Stone in 1 scene ..it can save and appear in scene display ..can someone help me
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Don't cross-post, use one channel only!
I don't quite follow what the issue is here, what is supposed to be happening?
Also, if you find yourself numbering variables, that is usually a sure sign you should be using a list
GUN CODE - https://gdl.space/qegisoqihi.cs
**ENEMY CODE -https://paste.ofcode.org/344br3pcPHRXTJY2tHG6ZCu **
THE PROBLEM - The bullets don't hit the enemy, what to do?
Neither of these seem related to bullets hitting enemies
Do you have a script on the bullet perhaps?
Also what components does the bullet have and the enemy?
Also this is weird:
if (hit.transform.tag == "Enemy")
{
hit.transform.gameObject.GetComponent<EnemyController>().health -= Random.Range(hit1, hit2);
}```
It seems like you're spawning a projectile but you're also doing this and using a raycast?
The bullet doesn't have a separate script, I just put a prefab of the bullet and set a shot point.
So, first off, why are you spawning an instance of a prefab, and then adding in a bunch of components to it? Why not just put those components on the prefab
Sorry I'm a beginner, that's why I came here...
Second, log the object your raycast hits. If you're getting bullets to spawn at all, then the ray is hitting something. That thing might not have the Enemy tag
I thought it would be more convenient
I tagged it enemy
Does anyone have a solution to fix this? There is no clear enough guide on the Internet
Log the object you hit and see if that object has the tag "Enemy"
I already did that
And what did it say
What does that mean? 
I literally do not know how to put this any more clearly than asking you what your log said
And where did you put the log
In this part
void Die()
{
Debug.Log("Enemy died!");
// Additional logic for enemy death can be added here
Destroy(gameObject);
}
}
That's not what I said
Log the object your raycast hits
see if that has the tag Enemy
But I already tagged him an Enemy!
And how do you know
how do you know that the ray hit that object
You're assuming your Raycast is hitting the enemy. How about instead of being stubborn you actually add logs so you can fix your problems
That's not what I asked
At no point did I ask "Is there an object in your project tagged Enemy"
I asked "Is the object your raycast hits tagged enemy"
Now put the fucking log in
and no
🤔
@rich egret If you're not going to actual log your issue, as you've been asked multiple times, stop posting.
@frosty hound 🫣
Put in the log.
Show what it prints
Until you do, no one can solve your problem
I place this here since i kinda think this may be via code, but. I have a particle system that triggers when you have contact with an enemy, the thing is, it's supposed to be blood. But if u move when the particle system is working, the blood will stay where you walk, how can i make the particle system to not move after being executed? Or what's the line of code to execute it at a certain location
There's a checkbox for something like "Simulate in world space", where the particles are no longer bound to the parent object after spawning
Particle systems have a property for simulating in world space.
Thank you both
I already put it, but I don't receive messages, something is wrong with the script...
Where did you put it
Btw, this
#💻┃code-beginner message
Is NOT what they want logged
They want the RaycastHit logged just after the raycast, before any of the conditions
Log the object you hit
then check the tag
We already know this is not running
that's why I told you to log the object your ray hits
not inside an if
Log the raycasthit (not a random word) "Before" any conditions.
Where is it located?
Pretty sure it's in main
I opened all of the things and i dont find it
Ohhh Simulation Space
and then u place it on world
ty
ok like this? @polar acorn
how
how did you possibly think this was related to what I asked
The log should be inside the gun script, just after the line you call raycast. And it should log the object returned by the raycast (called a RaycastHit). You have it declared as "hit"
we do not need to print if this object's Update is running. That was never the question. At no point did anyone say anything remotely related to doubting if this object exists.
Log
the
object
like this?!!!!