#💻┃code-beginner
1 messages · Page 542 of 1
yes (RigidBody2D is at hero)
so i should change the layers to default?
nope, if you didnt change the matrix, when you create a layer it interacts with everything BY DEFAULT, such as the default layer.
screen your rb component
ok this should work... you didnt make it local ? https://unity.huh.how/physics-messages/local-functions-2d
no, i didnt make it local
Try private void OnTriggerStay2D(Collider2D other)
instead of private void OnTriggerEnter2D(Collider2D other)
maybe your are moving via transform, so you bypass the physic logic
it is just for debugging, if this works you should improve this because on trigger stay will be triggered every frame
its dont work after change for private void OnTriggerStay2D(Collider2D other)
I Mean nothing changed
damn... And on console and editor no warnings/errors ?
Your Rigidbody type is Kinematic which means it is ignored by the physics system
so what i should do?
change it?
when i change for dynamic my hero go down and down, but when I set at static it still dont work
when you change to dynamic and it goes down it means there is nothing beneath it to support it
well i thought rb kinematic still make collisions... >>>Kinematic bodies also affect the motion of other rigidbodies through collisions or joints.
They are just not affected by others. So you are indeed right, the script can't process.
Your city have no rigidbody right ? Just a box collider trigger ?
Oh ok... So you must make the OnTriggerEnter2D on your city. Try it with the tag of your player.
This way you can keep your player kinematic
my pleaasure 🙂 i'm glad @languid spire got the point cause i missed it (im always making my scripts on my triggers so it was unatural for me to think about this)
Hi so im following this tutorial and am about21 mins in
In this video we setup the foundations of a finite state machine and create a basic patrolling behaviour,
Come Join us on the Discord!
🎮 https://discord.gg/xgKpxhEyzZ
Path Script : https://www.mediafire.com/file/no43lxga8wv0965/Path.cs/file
and im getting this error
when trying to run the movement
Hey, I didn't code for 3 years, and I'm trying to get back into coding. I want help with figuring out why the "If, else" isn't working.
you have a semicolon next to your else,
I get a new error now
this problem is on line 46
Well you should have no mesh agent component on a waypoint, click the error and share the relevant script part
nvm, fixed it, there was a semicolon that wasn't supposed to be there. Thank you
also check #854851968446365696 for VS autocompletion
Is it okay if i send it at 3pm gmt
i am in school so i cant really work on it that much
then don't post before you have time 🙂 there is always be some helpful people here no worries
just a small tip : when you get a component check that its not null before processing with it
if(gameObjectToCheck.GetComponent<Rigidbody>() != null) { //do something }
I would question why a Waypoint would have a NavMeshAgent component in the first place
And i did the same 😉
i think he tried to getcomponent instead of player.getcomponent
if you're going to do that, use TryGetComponent<T>() (Link)
📃 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. Use a paste site
📃 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.
On it my apologies again
Yep it's cleaner, but for a beginner out is kind of confusing (they know much more operators than use of out)
seems like a small thing that they can learn about quickly
at the bare minimum cache the get ;p
This is a coding channel, not sure why you ask here
Seems self explanatory too
Okay thanks. But how can I make it so that clone only make one clone
LaserBeamManager:
• only one in the scene
• detect when key is pressed. Instantiate a LaserBeam
LaserBeam:
• can have multiple in the scene
• moves forward
• when touching an enemy, damages it
Oh ok thanks
Hey all! Just wondering if there is an effective way to determine clicks on canvas elements, potentially similar to a raycast? Currently I am working on a menu system and I'm not sure if I should be creating an "Interactables" list (containing anything that can be clicked) which I loop through to compare distance of each element on click, I assume that there's a wildly more efficient way of doing it. Any ideas would be greatly appreciated!
Looking a bit further I've found the "GraphicRaycaster" which seems to be what I'm looking for!
you probably want a GraphicRaycaster https://docs.unity3d.com/2017.3/Documentation/ScriptReference/UI.GraphicRaycaster.Raycast.html
😄 yeah
Haha funny timing!
combine with the IPointer interfaces
yep there are those at well if it makes sense to manage your selection from each object (I don't think that's very often the case in reality)
I see, I'm trying to update canvas elements on hover which it seems like there's a OnPointerEnter/Exit function which seems perfect for that 😁
hey every time i change somthing in the script unity takes a whilee reloading stuff, anyone know how can i speed that up?
you can, but there are a few gotchas:
https://docs.unity3d.com/2021.3/Documentation/Manual/DomainReloading.html
You can also turn off automatic domain reloads in Preferences, and then manually refresh with CTRL / CMD + R.
Doing it manually saves you So much time.
if it's because you have a lot of scripts or packges you can use asmdefs to limit what gets recompiled
mmm still when reloading it takes the same time
i just started, only have like 5 scripts
just changing 1 value it takes a loot
It needs to recompile everything in that assembly because other scripts could depend on that "1 value"
Yeah, it just helps with the frequency. You can use assembly definition files to cut down on the time.
Dont think assembly definitions help much if you have 5 scripts 😄
Useful for later for sure
Missed that part 👀
Although, what are the odds they "have 5 scripts" and forget to mention 20-or-so asset packs 😅
Yeah
i only have those scripts, one texture and one material 😆
Speaking of, it doesnt only recompile scripts, it could also be running OnEnable/Awake on some assets etc.
where's this option? i can't find it
is it in the global prefs or project settings?
Ah yeah, my bad 😅 Forgot the exact name of it
In my open world car drifting game I added a script to change the color of the car by clicking UI buttons. I have red, orange, yellow, green, blue, purple, white, and black color options. Literally every single one works except for the orange color option. It's coded just like all the others and the button is set to activate the correct method, but every time I click the orange button it makes the car yellow, the same exact shade as my yellow color option. Any ideas why only the orange one isn't working?
public class CarColor : MonoBehaviour
{
public Material carMaterial;
public AudioSource audioSource;
void Start()
{
carMaterial.color = new Color(0, 0, 0);
}
public void carColorRed()
{
carMaterial.color = new Color(255, 0, 0);
audioSource.Play();
}
public void carColorOrange()
{
carMaterial.color = new Color(255, 128, 0);
audioSource.Play();
}
public void carColorYellow()
{
carMaterial.color = new Color(255, 255, 0);
audioSource.Play();
}
public void carColorGreen()
{
carMaterial.color = new Color(0, 255, 0);
audioSource.Play();
}
public void carColorBlue()
{
carMaterial.color = new Color(0, 0, 255);
audioSource.Play();
}
public void carColorPurple()
{
carMaterial.color = new Color(255, 0, 255);
audioSource.Play();
}
public void carColorWhite()
{
carMaterial.color = new Color(255, 255, 255);
audioSource.Play();
}
public void carColorBlack()
{
carMaterial.color = new Color(0, 0, 0);
audioSource.Play();
}
}
that could be a lot of things
did you check all the links throughout?
wdym by links
make sure you've made the button call the right method
button -> click -> method -> color -> set color
yeah and I've checked the "orange" method with debug.log and it is being called when I press the orange UI option
make sure you've saved all your files.
yup they are
I'd slap a breakpoint in both carColorYellow and carColorOrange to see if the wrong one is being called, or perhaps both are being called.
the only thing I can think of is that the RBG color code I put in might be wrong
but it's the same color code as the color of my orange UI button
lemme debug.log to see if the yellow method is being called also
50% is a pretty large difference. you'd be able to make that out if it were set correctly
Learning to use breakpoints in the debugger will make your life a lot easier 😁
try logging out carMaterial.color right after you've set it, right after the Debug.Log("orange")
hmm only the orange method is called when pressing the orange UI, and only the yellow is called when pressing yellow
I'm gonna try some different RBG codes in the orange method to see if those work
In the orange method I put the color code (255, 128, 0) for orange and when I click the orange button it debug.logs that same exact code, but the car is yellow
do any other non-0/1 colors work
new button, new method, new everything
try new Color(128, 128, 128), see if that makes it gray
...wait
Color takes floats between 0 and 1
not ints between 0 and 255
Apart from the fact that your structure is horrible. You should be using Color32
I just tried 255, 100, 50 and it made the car white 💀
yeah, anything above 1 is gonna be treated as 1
I'm not here for people to crap on my beginner code so leave
you're thinking in ints, but Color thinks in floats
i mean, if you want to use ints between 0 and 255 then you should use Color32, yes
you can also just use Color.red etc
ah I get it
I don't think it has anything to do with ints of floats,
Color is 0 to 1
that's weird that it's 0-255 in inspector but 0-1 in code
What threw me off was that supposedly the other colors worked fine ???
yeah, in floats
because 255 has the same behavior as 1, which is what they were going for
because all the other colors are either (255, 0, 0), or some other variation of one channel being max and the others being zero
so the code just treats it as 1, 0, 0
probably because those are Color32s
when I do orange, I typed 255, 128, 0 and the code treats it as 1, 1, 0
they can be implicitly converted to and from each other
Well yes, but surely your purple cannot have been purple
it's actually magenta, so that worked fine
it was 255, 0, 255 and code treats as 1, 0, 1
I guess I'll change everything to the 0-1 system
I'm glad you figured it out :D
Hi, how to do something like, when i click a button my countCoins degresse by 5 ?
have you tried searching about that at all?
that's a pretty basic thing, there should be plenty of online resources about that
Have a look at
https://learn.unity.com/pathway/unity-essentials
yes but always its show how to do in one script and i think its really bad if i want to do this for a lot of items
ok... ask about that then
everything works!
if you just ask about that specific problem then you're going to get a specific answer
if you're stuck on how to generalize it, ask about that
what does "a lot of items" mean?
If you want to simplify your code a bit, you can do something like
ColorUtility.TryParseHtmlString(color, out Color newColor);
material.color = newColor;
}```
Then you can set the hex value directly in the inspector for the OnClick event,
eg "#B43B21"
I usually find html color codes a bit easier to work with
aw man i got so excited for a sec, until i realized it was html colors and not css colors
Are they not the same thing?
TryParseHtmlString will take any hexadecimal color value and return the color
no, it's just referring to hex color strings and a few basic keywords here
css supports a lot more formats
rgb, hsl, hsv, and some other color spaces with function-like syntax, and keyword colors
though i guess that would be an absolute pain to fully implement since it'd have to support like css math too
I'm just gonna stick with the code I have for right now, it does what I need it to 🙂
i'd really recommend toying around with what half spacer showed. it'll allow you to make the functionality more generic (ie adding more colors or allowing custom colors) and it's also an exercise in making future-proof code in general
hardcoding everything leads to hard walls to changing those features
you have a lot of duplicate code there, why should it all be repeated when only one part changes? that's like, the key sign of something that should be a function
how do I use this? Just paste this into the script and have the UI buttons call it?
sure
Yup yup :)
don't forget the audiosource
When you select the function in the UnityEvent in the inspector, you'll get a little input field for the string value
👍
ok I put the code in and deleted my other code and I assigned each button to its own hex code but now every single button makes the car white
public class CarColor : MonoBehaviour
{
public Material carMaterial;
public AudioSource audioSource;
public void SetHexColor(string color)
{
ColorUtility.TryParseHtmlString(color, out Color newColor);
carMaterial.color = newColor;
audioSource.Play();
}
}
What do your color codes look like?
make sure to read the docs too https://docs.unity3d.com/2020.1/Documentation/ScriptReference/ColorUtility.TryParseHtmlString.html
here's the one for blue
Remember the #
hi guys, anyone can take a look? spent two days on this, my first game try 😅 https://stackoverflow.com/questions/79275559/c-sharp-unity-how-to-properly-deal-amage
oh yes hold on
it works now thanks
Put your code into paste sites please, scrolling those small code windows in stackoverflow is a bit annoying
!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.
Anyway, to me it seems like you are just always attacking/starting a new attack coroutine when in range.
You probably want a cooldown timer
Or does canAttack take care of that 🤔
Is this AI code btw?
a powerful website for storing and sharing text and code snippets. completely free and open source.
could you paste the log you get in TakeDamage, and ensure you only get it once when you expect it once
Hey, I've got an issue with the input system. My interaction when being held is getting called when I Tap the button. I am not too sure whats happening and I am having trouble finding a solution online as well. https://pastebin.com/sN0rfNsJ
Thanks
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
its weird the coro in player script works fine
Well it says that the health is 0 beforz damage
true, but i dont understand why
the coro i added in the playerscript for debug works exactly as it should
Find references to currenthealth to see if something else change the variable ?
How can i Destroy() prefabs that are instantiated in a different Method?
When i do this:
GameObject P1Coins = Instantiate(coinprefab, ...)
Destroy(P1Coins) }```
It works, but when i do this:
```void Method1 {
GameObject P1Coins = Instantiate(coinprefab, ...) }
void Method2{
Destroy(P1Coins) }```
I know that this is because the variable is not defined in Method2, however i dont know what i can do. Creating a GameObject before all the Methods also does not seem to work
Can you add a log in setHealth() ?
move P1Coins to the class scope, so the entire class shares the field
though keep in mind that if you call Method1 twice you won't be able to destory the first one, since the variable would get overridden. if you need to manage many objects then use a list
I tried this but it does not seem to work
what do you mean by "doesn't work"
You did it wrong then
private GameObject P1Coins;
private void Method1 { P1Coins = Instantiate(coinprefab, ...); }
private void Method2 { Destroy(P1Coins); }
So this is my entire code, excluding all of the other fields. I want it to remove a coin (The ones you get from the StartCoins Method) and from all coins that are instantiated. It really could be that i am missing something here
GameObject P1Coin;
void Start()
{
boxot = FindFirstObjectByType<BOT_Behaviour>();
StartCoroutine(Startcoins());
}
IEnumerator Startcoins()
{
for (int i = 0; i < 10; i++)
{
yield return new WaitForSeconds(0.2f);
GameObject P1Coin = Instantiate(coinprefab, new Vector3(1.531f, 2.223f, 2.234f), Quaternion.Euler(90, 0, 0));
AudioSource.PlayOneShot(sfx_win);
}
}
public void RewardCoin()
{
AudioSource.PlayOneShot(sfx_win);
GameObject P1Coin = Instantiate(coinprefab, new Vector3(1.531f, 2.223f, 2.234f), Quaternion.Euler(90,0,0));
}
public void LoseCoin()
{
AudioSource.PlayOneShot(sfx_lose);
GameObject P1Particle = Instantiate(particle, coinprefab.transform.position, Quaternion.identity);
if (coinprefab != null)
{
Destroy(P1Coin);
}
else
{
Debug.Log("No more Coins left");
}
Destroy(P1Particle, 1f);
}
could the coinprefab != null be the issue? If so i apologize
from all coins that are instantiated
you didn't read my second message then
What is coinprefab (it's not included in the code)
it looks like is never called, indeed i have only setHealth function but not used
And what calls LoseCoin() ☝️
also, you didn't move P1Coin to the class scope. you duplicated it to the class scope.
im getting deja vu
Ah i oversaw that, thank you!
Its called outside of the script by another
#💻┃code-beginner message @tulip nimbus
Oh yeah i had a similar question it was about them as a whole, at that time my code was a bit simpler i appreciate it
Maybe you should encapsulate currenthealth with a property so that you could log evrytime health is modified.
Check your serialized field too on your player, but the first log seems ok...
so i found something. i recreated everything from scratch. the first time i run the code it works.
then if i stop the player and press play again, currentHealth is set to 0
public class PlayerHealth : MonoBehaviour
{
[SerializeField] private float maxHealth = 100f;
[SerializeField] private float currentHealth = 100f;
[SerializeField] private Slider healthSlider;
private void Awake()
{
// Initialize health
currentHealth = maxHealth;
Debug.Log($"Initialized Health: {currentHealth}");
// Configure the slider
if (healthSlider != null)
{
healthSlider.minValue = 0f;
healthSlider.maxValue = 1f;
UpdateHealthUI();
}
}
so maybe a problem in currentHealth = maxHealth; this line of awake? sorry but im new to unity
i tried to remove [SerializeField] from currenthealth but it always starts at 0
With that tag there, it means you would set the value in the inspector for this object. When the object is first spawned in, currentHealth will become maxHealth, so there's not really any point setting currentHealth in the inspector. You should remove that tag
yeah looks like the inspector fucked me up
now i just have to find why slider UI is not updating lol
and that = 100f is unneccessary too
thanks guys

The inspector is designed to take precedence over the code, otherwise you wouldn't be able to set any values in the inspector at all
Do you have any scriptable object ? because everything should be the same everytime you hit play
well, the currentHealth = 100f yes, but the maxHealth = 100f not really. that's the default used when you newly add that component to a gameobject, so it's effectively the default
Hi. im starting right now with Untity, but im not able to find some good websites or youtube channels. Do somebody know some?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah i meant for the currentHealth 👍
so ive been playing around with it again.
looks like the problem is that currentHealth is retained between each time i press Play. even if currentHealth is not serialized anymore. ive been reading the unity forum, maybe im changing the value to the prefab itself?
Are you referencing the prefab or the instances in the scene?
here is everything
https://paste.myst.rs/5ft7ef6v
a powerful website for storing and sharing text and code snippets. completely free and open source.
Nothing in here calls SetHealth. Is that function even running
nope, but now enemies deal damage fine. ill remove it as it is unused
Ah, you're also changing it in TakeDamage I see
so the problem was that currenthealth is retained from the old value when i play/stop and play again
Which is called in EnemyMovement, on the PlayerHealth component of player. What is player set to on EnemyMovement?
it is the transform im using to calculate distance between enemies and player
Is player a reference to an object in the scene or a prefab
So it's a prefab
because im spawning the player with char spawner script
You're modifying the health of a prefab there
For this component, instead of referencing a prefab, reference the player in the scene
Hello, do you guys know why my codes aren't working with Unity ? I've set my script editor to VSC and when I make a mistake in my scripts for example type Debug.log with log lowercase then it gives an error, but if I write it correctly Debug.Log then it doesn't print the message coming after, I would really appreciate any help.
If nothing shows up in the log, then that line isn't running
It's under the Start() function tho, it should run
And is there an object with that component active in the scene?
so i drag my prefab in the scene, i set it and then remove it from the scene as i use the spawn script?
I have to add a cube or something in game to make it work ? I am still a new comer to Unity so I have 0 knowledge about it
If you remove it from the scene, then what would you be referencing? You need to reference the player whose health you actually want to change
In order for code to run, it has to exist. You need to put the component on an object for it to run
I am confused by what you are saying, here is where my script is located
What object is it on
Idk, assets folder
That's not a GameObject
All the script has to do is print in the console that is all
If you want code to run, it has to exist
Right now, it does not
Your script defines a component
that component is nowhere
so it isn't running
Oh, I am still with the Roblox stuff since I am a former Roblox coder lol, in Roblox you didn't need to add them to objects for them to work
Surely they needed to exist somewhere in order to run. Code doesn't run unless something runs it
have you gone over unity essentials
No idk, I've been at the problem with the script for 3 days now lol
Let me try the stuff I got told above tho
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
my unit does not want to go into the attack state I have scripts that decide these states and an attack controller that references these scripts but now all of the sudden after i have changed nothing he doesn't want to go to the attack state I can see it through the animator tab the transitions are the same to when it worked beforehand
i coded in a room transfer, yet im being sent all the way out of bounds, not at the bush gate
does it have something to do with my coordinates?
well how are you spawning the player
have you tried adding debug logs to the state transfer to see why exactly it isn't transitioning
yeah 
But like, if you want to do some back end scripts like data stores and important stuff behind the scenes, how do you do them without adding the script to an in game object ?
i gave it the exact coordinates of where the gate was
You would probably not make them MonoBehaviours, which are components that are attached to objects
Or, if you need to use Unity MonoBehaviour messages like Start and Update, you'd just put them on an object
I see, thanks for all the help you've provided ! Helped me a lot
yeah the player spawns somewhere else, idk how id find the exact coordinates
open the scene view and select the player
show the code where you're spawning the player maybe
Hi im comming back to unity after learning a bit about a year ago and thought i make a flappy bird game from scratch.
I have created a game character and created a prefab with two rectangales to make the gate for the bird to fly through.
my bird can fly up and down and I am moving my pipe from right to left but getting frustrated with the collision . the bird can sit on top of the pipe but if he hits the side part of the pipe he goes straight through.
|
Any ideas
yeah i got an idea, you're not moving the bird (or the pipes) with rigidbody physics are you?
yes getcomponent<rigidbody2d().addforce
then perhaps the collider on the pipe is not the right size?
i know
what?
i created one rectangle to test this further collider covers the rectangle. same thing the bird sits on top but if i position the bird to the side the rectangle moves through the bird
and I get debog.log message saying character collider with rectangle
can you show your scripts?
whats hte math for converting a linear function into an exponential one while keeping the limits the same
idk if thats the word, i mean the boundaries
Please can you remind me how to format my scripts into chat
!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.
currently got
var magnitude = Math.Min(Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2)), LAUNCH_DRAG_CAP) - RELEASE_THRESHOLD;
, using it for scaling an object and want to convert it so it scales along an exponential
'''cs
using UnityEngine;
public class PipeMove : MonoBehaviour
{
private Rigidbody2D rb2d;
public float speed = 2f;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
if (rb2d == null)
{
Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
enabled = false;
return;
}
// Ensure collision detection is continuous
rb2d.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
}
void FixedUpdate()
{
// Move the pipe using velocity for proper collision detection
if (rb2d != null)
{
rb2d.linearVelocity = new Vector2(-speed, 0); // Move left
}
}
void OnCollisionEnter2D(Collision2D collision)
{
// Optional: Detect character collisions
if (collision.gameObject.CompareTag("flappy"))
{
Debug.Log("Character hit the side of the pipe!");
// Additional logic can go here if needed
}
}
}
'''
'''cs
public class flappyFly : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(Vector3.up*6);
}
if(Input.GetKeyUp(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(Vector3.down*-2);
}
}
}
'''
` not '
I have to admit I did try with GTP to fix the situation so the code was adapted by the app
Thanks
code for scaling rn is
var base_x = Mathf.Sin(angle);
var base_y = Mathf.Cos(angle);
var target_x = base_x * Math.Abs(Math.Clamp(dx, -LAUNCH_DRAG_CAP, LAUNCH_DRAG_CAP));
var target_y = base_y * Math.Abs(Math.Clamp(dy, -LAUNCH_DRAG_CAP, LAUNCH_DRAG_CAP));
var arrow_scale = (float)magnitude * ARROW_SCALE_CAP;
aim_arrow.transform.position = this.transform.position + new Vector3(base_x * Mathf.Max(arrow_scale, 1), 0, base_y * Mathf.Max(arrow_scale, 1));
aim_arrow.transform.rotation = Quaternion.Euler(new Vector3(90, angle * (180/Mathf.PI), 0));
you gonna fix it?
yes
Hey I am building some mini games to learn and improve, right now I am trying to build a little round based combat sample with and overworld.
When the character touches an enemy, I load the scane with the batlle UI and the fight takes place. After the fight I want to return to the previous scene in the overworld, to the spot where my character touched the enemy.
When I load into the previous scene, the whole scene got reset. Ofc I can save the position of my player and just put him there, but is there a best practice to this case? Do I really have so save everything, every position of every enemy, every switch that I flicked, etc etc when I just want to return the the previous spot?
using UnityEngine;
public class PipeMove : MonoBehaviour
{
private Rigidbody2D rb2d;
public float speed = 2f;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
if (rb2d == null)
{
Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
enabled = false;
return;
}
// Ensure collision detection is continuous
rb2d.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
}
void FixedUpdate()
{
// Move the pipe using velocity for proper collision detection
if (rb2d != null)
{
rb2d.linearVelocity = new Vector2(-speed, 0); // Move left
}
}
void OnCollisionEnter2D(Collision2D collision)
{
// Optional: Detect character collisions
if (collision.gameObject.CompareTag("flappy"))
{
Debug.Log("Character hit the side of the pipe!");
// Additional logic can go here if needed
}
}
}
using UnityEngine;
public class flappyFly : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(Vector3.up*6);
}
if(Input.GetKeyUp(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(Vector3.down*-2);
}
}
}
wait fuck im stupid i need to adjust acceleration
not scaling
ok can you show the collider on the bird and pipe?
eh whateve ri still need a linear -> magnitude converter
oh wait nvm theres a problem here, you're using addforce in update instead of fixedupdate. get input in update and then do the addforce in fixedupdate
can you serializefield a const
@cosmic quail im asking because it seems to silently fail stinker
and i refuse t oaccept "just dont use consts" as a solution
if i google your question it immediately says "Unity can serialize any field except static, const, or readonly fields."
hot
Consts are fine, but if you can change it in the inspector then it's not very constant is it
why though?
because having to edit these from the text editor is annoying
consts are a compile time concept so serializing them for run time would make no sense
If you want to edit them, why are they consts? Stuff like those bitmasks definitely look const-like, but also probably should just be a Flags Enum
Stupid question here what's the (1<<2) stuff?
oh taths whta serializefield does? thought its just "get around private modifiers"
bit shifting
Oooh
Bit Shifting.
https://unity.huh.how/bitmasks
A bitmask is a representation of many states as a single value.
i want to edit them only in the editor
on runtime they should stay as they are
If you want them all modifiable from a single place, consider making a ScriptableObject that hass all the values you want, and storing them in an asset.
no
using UnityEngine;
public class flappyFly : MonoBehaviour
{
private Rigidbody2D rb2d; // Cache the Rigidbody2D component
private bool isPressingSpace = false; // Track if the space key is held
private bool spaceKeyReleased = false; // Track if the space key was released
public float upwardForce = 6f; // Force applied when space is held
public float downwardForce = 2f; // Force applied when space is released
void Start()
{
// Get and cache the Rigidbody2D component
rb2d = GetComponent<Rigidbody2D>();
if (rb2d == null)
{
Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
enabled = false;
}
}
void Update()
{
// Check if space is pressed
if (Input.GetKey(KeyCode.Space))
{
isPressingSpace = true;
}
else
{
isPressingSpace = false;
}
// Check if space was released
if (Input.GetKeyUp(KeyCode.Space))
{
spaceKeyReleased = true;
}
}
void FixedUpdate()
{
// Apply upward force if space is held
if (isPressingSpace)
{
rb2d.AddForce(Vector2.up * upwardForce, ForceMode2D.Force);
}
// Apply downward force if space was released
if (spaceKeyReleased)
{
rb2d.AddForce(Vector2.down * downwardForce, ForceMode2D.Force);
spaceKeyReleased = false; // Reset the flag
}
}
}
still the same, I assume this is what you meant
They still wouldn't be const, but it seems like you don't actually want consts anyway
Ooh that's what layermask are pretty cool, you learn something new everyday
so if i want qol i shouldnt use consts
thats sad
If you want to change the values, you shouldn't use constants, which are defined by their inability to be changed
hmm well what do your colliders look like?
yeah i DONT want to change the values
i want to modify them on compile time
and keep them as is on runtime
you should use consts when you want consts
what you want is something that is runtime const but not editor const
which i CAN do by tweaking the code
Then change them in code, like you would with any other programming language.
and im complaining that i cnat do that in the editor
make them private then
But you want to serialize them to a file and deserialize them. That's not a thing consts do
Why do you need them to be consts?
because im not planning to change them on runtime???
that's not what const means
so slap a const on top???
Okay, but why do they need to be const
a const field means it doesn't change ever
then why serializefield?
Are you trying to use them in a field initializer?
Are you trying to put them in some other compile-time use case?
idk?
all i was taught about it was "heeh. use it when the var is private so you cna still edit it in editor"
@flat sphinx by "change at runtime" do you actually mean like, runtime in code, or in play mode in the editor
I have a prefab with a collider around both green rectangles and a empty trigger in the middle to register going through
just get rid of the serializefields and edit it through the script if you want const
Question, I have a development-only prototyping room, that is getting 200 FPS because their is pretty much nothing in it, my issue is that the players input is delayed at that 200FPS, but is fine at 60FPS. Why is that?
is there a difference?
are you perhaps reading input in fixedupdate
yes
do they have rigidbodies?
Yes, i needed to do this to fix rigidbody jitter.
input is frame-bound. fixedupdate is not
Input should not be done in FixedUpdate
So switch it to Update?
you should read inputs in Update and the actually movement of the rigidbody should be done in FixedUpdate
Read input in Update, move rigidbodies in FixedUpdate
did not think this would be the difficult bit
@flat sphinx when you say you don't want to change it at runtime, do you mean that you want to make it grayed out in the inspector while in playmode in the editor, or disable modifying through other code that is executed while in playmode/build
Oh, i see what you mean.
sorry I probably missed something but what exactly is the problem?
my bird can sit on top the my rectangles but passes through the side
i dont care to modify it in any way through code
i just want to be able to tweak it in the editor, even if only in edit mode
or whateve the not-play mode is called
Editor mode
then const isn't even relevant here
Yeah const means it will never change in editor or runtime?
that's certainly interesting. Sorry I don't have an answer for that. I'm still not expert at unity myself 😕
const is about how the code acts internally to itself, unrelated to the unity editor
are bird and pipe both set to kinematic?
const means it is a compile time constant. Code only compiles when a script file changes. Changing the values of assets does not cause code to recompile. Changing a value in the editor is antithetical to what const means
sigh
time to shittify my code for some dx i guess
I am coming back so thought I would test what I remembered failed at first project 😦
i dont think addforce can be used for kinematic
god forbid we let unity change a script file
It's not a huge deal fortunately
yes... because that's not how c# works
keep the pipes kinematic and bird non kinematic
that would be a massive pain actually
?
file io is file io
add force i think is for the bird (flappy he is dynamic)
If your code did exactly what you want it to do, you'd be here complaining that every time you type a value in an inspector window you had to wait several seconds for the domain to fully recompile
and most editors have hot refresh anyways
and it'd have to recompile instead of just setting values
and yknow, it'd break any formatting that the fields had to begin with, since formatting isn't kept when stuff is compiled
Seems to me like you just got told "use const as much as possible or your code is bad" and never actually bothered to learn what const does
uhhuh
except for debugging i guess
marking something that does change as const just doesn't make sense lol
Yep, this fixed it.
idk why you're making this a big deal, const is not that important
this isn't js where const is necessary
good!
It literally just gives you access to the variables in compile-time use cases like field initializers and parameter defaults
It doesn't even give any noticeable performance increase
Because floats are value types already
Thats is how they are set up
am coming from a shitlang where i need to #define code chunks instead of making them a function because proc overhead is stupidly slow
also just ocd
Well, no noticeable performance increase over static variables at least. If they're non-static you could have redundant copies
ah. relatable.
But a ScriptableObject or static class would serve the same purpose
maybe
but i also dont like spamming classes if i dont need to
It's an object oriented language, that's kind of what it's designed to do
if it helps, think about this;
c# usually has 2 steps, compiletime and runtime
but unity adds another step in between, where it injects values set by the editor
const doesn't really fit into the picture that unity sets
const is for "constant", and stuff that's set by the editor can't be constant, otherwise the editor wouldn't be able to set them
yeah but i dont need an object in an object to store some 5 consts that are in the parent object anyways
does the bird's collider look ok too?
yeah that makes sense
Probably not. Just pointing out ways you can eke out tiny bits of performance if that really was the concern
i mean eeking out performance is just setting them to const
But we're talking literal bytes of memory in an era where you can get 16GB of RAM for the price of a chicken sandwich
const would be for true compile-time constants, that aren't game parameters, stuff like how many minutes are in a day, how long some code-specific buffer is, what version of the game you're on, that kind of stuff
this is JUST ocd
wtf why are your chicken sandwiches so cheap, get me some of those
cant remember this being such an issue before::
does const even do anything at runtime
well it shouldnt be an issue, you probably forgot something?
something something compiler magic
it's a modifier, is it not just a compiletime thing 
granted its more of a nudge on stuff it probably already knows
i guess it would improve branch prediction? but this stuff you can't really control anyways
but also; stuff you never assign to can be "effective consts", and the compiler can optimize them just like actual consts
that's a thing in java, and i think c (gcc), not sure if that's a thing in c#
it probably is

i mean theres also the "not storing a copy for each instance" but that you already get from statics
i think consts you could optimize down into.. well, consts, in assembly
but this is cshart so thats not it either
its like static where all instances of the script have only one of it stored in memory in total right?
PUSH 50 instead of PUSH %EAX or however assembly works
dont remember jack shit from it lmao
How can i enable/disable a render feature from a script during runtime?
no, consts are instance-specific i think? (or is readonly a different thing)
nope, usage of variables declared as const are replaced with their constant value at compile time
constants are not instance variables, you're thinking readonly
Thank you for your help I am going to follow a flappy bird tutorial to see how its done and compare to my effort
imagine every flappy bird game was published somewhere 😉
im confused as hell man does anyone else know whats going on here?
the bird can stand on a pipe but when going through the side it goes through???
The pipe moves right to left and the bird up and down
The pipes themselves could be moved in a way that does not respect physics
Like by altering transform.position
he showed his code, he used linearvelocity for the pipes and addforce for the bird
and they were both in fixedupdate
Then the colliders are not setup so they interact correctly. Both need to be non-trigger ones
I starting to think that its going to be a mac silicon issue
probably not something this simple
But since you lose when you touch a pipe, you can get off with having the pipes as triggers, and check in OnTriggerEnter2D on your player
the only trigger is an empty box in the middle
the pipes detect collisions as the bird flys through so that not an issue, I could continue to code I was just not understanding the glitch
maybe you changed the number of physics steps or something in the project settings
I have tried from scratch twice - I have two projects both do same thing
(what was the glitch)
I am using Universal 2D core template to begin the project
My bird character can sit on top of my rectanglke but pass through the middle
...and the rectangle is a rigidbody + collider?
isn't that what's supposed to happen
oh wait
middle as in, through the pipe?
yeah
yes
ive been thinking you meant between the pipes lmao
i was so confused
are the pipes a single rigidbody or 2 separate rbs
the top and bottom have there own collider and rigid body
How can i enable/disable a render feature from a script during runtime?
by this do you mean they had the same issue or not
passes through the middle of the pipe but can sit on top
been driving me crazy
you mean this? https://docs.unity3d.com/ScriptReference/RenderSettings.html its a static class, you can just reference it
are they boxcolliders or platform colliders
box collider 2d
and they're extended along the size of the pipe?
could it be cause the pipes are scaled? also why is the bird's scale 0.2
wait isn't it just because that's how kinematic rbs work
kinematics aren't simulated, they just move and dynamics can collide with kinematics
the dynamic shouldnt go through it though?
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.
the collision doesn't stop the pipes from moving left
and the bird is constrained on the X axis
so they're just forcibly phasing through each other
Having trouble setting Materials to an array? my array size is getting set but the materials are not(in the editor)```cs
public class ShipCore : MonoBehaviour
{
public Material[] MaterialArray = new Material[3];
public Material Material;
public Material TransMat;
public Material ThrustEmission;
public void Start()
{
MaterialArray[0] = Material;
MaterialArray[1] = TransMat;
MaterialArray[2] = ThrustEmission;
}
}
}
have you tried just adding OnCollisionEnter2d messages to debug
why are both the separate values and the array serialized here? what's the source of truth that you're setting the editor?
does the bird have a fixed x position by any chance
detects collision
then yeah collision is fine
if it works like that, how would you prevent players from going through moving platforms then? or is the X axis constraint causing this
they're just phasing through each other
it's the X axis constraint
🎉
he was spinning so tried to stop it
you only need the freeze rotation for that
i didnt even know it was constrained on the X axis, how would the bird even jump then?
wow thank you
jumping is moving along the y axis
y would prevent jump
x axis fixing would be fine as long as the game stops as soon as the collision happens and the bird falls in place
oh, i see
i'm guessing you're following the GMTK tutorial
no i am trying to figure it out my self
i did a bit of unity a year ago
but i did turned to chat gpt who made my code fancier with error debugs built in ect
yeah maybe don't do that
was desprate, going to start again this time just freeze z lol
next job create a spawn manager 🙂
Hey. is there a quick way to go back to a scene in its previous state?
use the version control software that you are surely using since it is the sane thing to do in order to revert to a previous commit for that scene
no no i mean in game, so i leave the scene because a battle menu pops up (another scene) and then want to change back to the other scene
And when i use loadscene with the buildindex, the scene is completly reverted to it's start state
you need to set up some way to store the state of the objects in the scene. because just loading the scene again is expected to do what you are experiencing
Ah damn, I thought there would maybe be a quick way and I would not have to do this..^^ Thank you
How do you guys go about saving game progress to a save file (new file, all that) ? Like the current xp, inventory, would xml be good for it?
xml is fine, yes. or unity already has jsonutility built in to serialize to json. or there are plenty of third party options for serialization like json.net or message pack (which encodes to binary)
I'll look into them, thanks for mentioning
help my logic isnt logicking
shoot_blockers is reset immediately to 0 after shooting and that should only be possible through the update block
Try logging it after you change shoot_blockers in OnMouseUp. See if it's 0 after those changes, or if it's changing somewhere else
Since you just need to check if it's zero or not, you don't need to worry about printing it as binary to see which flags are on, but that could come in handy too
It's been a while since I've seen that much bitwise ops, looks like I'm back with C
Surely there's a more readable way of doing this
i mean its basic bit fuckery so it shouldnt not be shoot_blockers - AIM_LOCK_AIMING + AIM_LOCK_MOVEMENT
this is readable
ama throw a spare Debug.log tho just in case c# broke bits
The bitops are not, it hinders readability
We have enums here which can help
Assuming everything is the values you expect them to be
But that's a bold assumption to make
Or even bool variables lol
some messages will be blocked by the discord, for good reason
If, for example, AIM_LOCK_MOVEMENT is 0, then the result could very well be 0
Okay, so it's not zero after OnMouseUp. Where are you seeing it at 0
editor inspector whatever
if i drag and hold its 1
when i release it it turns to 0
only the update function unsets that flag
aka this
And update runs every frame
yeah?
You would never actually be able to see the value between an OnMouseUp and Update
So, if it's getting set to 0 in update, you're going to see it at 0
did you.. even read the code
im trying to check if the ball hasnt moved in the past .25 seconds
if it hasnt, unset the movement flag
Yes, and I see a place where you remove AIM_LOCK_MOVEMENT from it, which would remove the only thing that it's currently set to
clearly the issue is either how i compare the times, or how i measure them
yes
thats what i want to do
i just dont want it to happen immediately after release
oh okay i figured it out i just didnt reset the value on launch
also checked against hte wrong value being 0
yeah it works now
yay me
I spawn enemies (gameobjects) in my scene.
I want to save this scene in it's current state. So I created a list of gameobjects and put every enemy gameobject into that list, after scene change all gameobjects are empty. okay i get that.
Next approach was saving just the position data of the enemies and the prefabtype, so I can just iterate through this list, when the scene is loaded the next time and Instantiate all objects with the prefab and the position data. But I am not able to get the prefab data in runtime, is my approach totally wrong?
can anyone assist me im trying to setup my project and when trying to create a player prefab of my character with this script attached it wont let me
you need to be more specific than "wont let me"
at a complete guess, i'd say you probably need to read through this: https://unity.huh.how/script-loading-issues
my bad let me post the error
The error says You are trying to save a prefab that contains the script. which does not derive from monobehaviour
Please change the script to derive from monobehaviour or remove it from the game object playercontroller
Looks like you have a script attached to an object that does not derive from monobehaviour
If it's attached to an object it needs to be a MonoBehaviour
Looks like you have a script attached to an object that does not derive from monobehaviour
If it's attached to an object it needs to be a MonoBehaviour
have you gone through the link here yet: #💻┃code-beginner message
yea i did i appreciate it
so you've confirmed you have 0 errors, the component inherits from monobehaviour, etc?
heres my code i think i did it correctly
using Unity.Netcode;
using UnityEngine;
public class PlayerControllers : MonoBehaviour
{
couldnt post the whole code
Well, there's your issue. You're missing the entire rest of the class
!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.
well those are different classes
Okay, so it's a NetworkBehaviour. Does NetworkBehaviour inherit from MonoBehaviour
i replaced network behaviour with MonoBehaviour and it didnt work
well yes, you would have had many compile errors doing that (well, maybe just a couple)
Show a screenshot of your Console
ok one moment
apparently theres quite a few errors
in my console log in unity
let me start a new fresh blank project
or you could just, idk, fix your errors?
that's literally the reason you are experiencing this
and was step 2 in the link you said you followed the instructions from
So, all the way back in the beginning, when you were asked if you had any errors and you said no, you never thought that maybe you should actually check
That wasn't a rhetorical question, you can't add any components while you have compile errors
i got it to work! thankyou guys ur a blessing
are you using the new input system or legacy?
if the new have u used the input debugger to see if it is indeed not working at all.. or not working in the way u expect.. (just brainstorming)
i have an RC Radio i use for fun.. and it'll display on that website a certain way but in unity the mapping is a bit different.. (still works.. but not where i expected to see it)
can someone help me with one of my methods that doesnt work (im new to unity and its coding language)
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
ive tried many differnet things to see if it would work but it still doesnt
show us your code and what isn't working as well as any errors you are getting, if any.
!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.
heres the full code, no errors in it showing in the log
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the method that isnt working is the HandleSlide
you still haven't even said what the actual problem is
im sorry im un familar how im suppose to ask in this server
the problem is that when the slide method is used it suppose to move the player forward, but it doesnt work and i dont know why. changing to vector2.up or down works but left or right doesnt
what do you mean "it doesn't work" what does not work? do you mean it does not move the player in the expected direction? does it not move the player at all? you have to provide actual details
You're setting time elapsed to 0 right before checking if it's less than Animation Duration. This will always be true and your coroutine will never exit
it doesnt move the player at all
oh nvm I see it
i'm gonna go ahead and assume you are modifying the velocity of the rigidbody in a different component every frame which would, naturally, overwrite the velocity you've set at the beginning of that coroutine
so how do you think i should solve this?
you need to not overwrite the velocity for the duration of the slide. this component has a reference to the PlayerMovement component, which is where i assume you set the velocity each frame, so tell it when it can and cannot set the velocity
okay i will try to do this and see if it works
thanks for the help and suggestions!
Can someone help me with this script? I'm trying to make the code spawn a prefab every 1.5 seconds then after 0.2 seconds it spawns it again using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PeaSpawner : MonoBehaviour
{
public GameObject Pea;
public float Cooldown;
public float Cooldownset;
public float Timetorespawn;
public float Timetorespawntwo;
public bool Shooting;
public bool Reapeat;
public BoxCollider2D BC2d;
// Start is called before the first frame update
void Start()
{
Cooldown = Cooldownset;
}
// Update is called once per frame
void Update()
{
if (Shooting)
{
if (Timetorespawn < 0)
{
Timetorespawn = Cooldown - 0f;
UnityEngine.Object.Instantiate(this.Pea, this.transform.position, this.transform.rotation);
if (Reapeat)
{
}
}
if (this.Cooldown > 0f)
{
this.Timetorespawn -= 1f * Time.deltaTime;
}
if(this.Cooldown > 0f)
{
if (Reapeat)
{
this.Timetorespawntwo -= 1f * Time.deltaTime;
}
}
if (Timetorespawntwo > 0f)
{
if (Reapeat)
{
Timetorespawntwo = Cooldown - 0f;
UnityEngine.Object.Instantiate(this.Pea, this.transform.position, this.transform.rotation);
}
}
}
}
}
please share this again on a paste site -- !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.
(gdl.space is broken right now, so use another site)
ok
What is the problem?
You've described what you want it to do, but not what the issue is
am i allowed to post a video here?
yes, to show your problem
i will show it
alright
if (Timetorespawntwo > 0f) sounds wrong to me
this checks if the amount of time left is greater than zero
which would spawn a projectile every single frame
so im starting to get back into unity after taking a break, and one thing i noticed with this simple movement script is that the y velocity seems to sporadically change to these odd numbers, which i think might interfere with a jumping mechanic i want to add. Is there anyone who can give an explanation as to why is doing this?
Also, the two timers will get out of sync over time
assuming that you have them different values, at least -- right now they're both set to Cooldown
that's normal
those numbers are all variations of zero
1E-08 is 10^-8
which is one millionth
It's probably some other very very tiny number even when 0 is displayed
I fixed it 🙂
Sure, but they're very very tiny
well.. miniscule amounts above and below zero
but yes
it does its best damnit..
(╯°□°)╯︵ ┻━┻
cause what my plan was for my jump script was to just check if the y velocity was 0 and if it was you could jump otherwise you wouldnt be able to
which is probably the least effective way about doing it
that would let you jump forever if you jumped at the apex of your previous jump
pro-gamer moves ^
true i didnt think of that
you would want to check if you are grounded as well
the most common way I've seen is to test if there's ground beneath your character
if you do that method
i have tried this OnCollisionEnter method but it didnt seem to work for me
you could use a query method, like Physics2D.OverlapBox
This runs once when you hit something
you could also do a ray/spherecast
or on collision stay it was
if needed
i love my raycasts ➡️
You'd need OnCollisionEnter2D here, since this is 2D physics
ohhhhh
my current 2d character seems to use CapsuleCasts tho
and it could still be fiddly
i bet that was the issue
Physics messages are very commonly messed up
I used to struggle to make them work right
this explains how to use them very nicely
well not really as you still were using the enter method
which is only called once
i typed it wrong
i was using oncollisionstay
i just mixed them up
using UnityEngine;
public class GameRush : MonoBehaviour
{
public void GoldRush ()
{
FindObjectOfType<GameManager>().GameEnd();
}
}
it just dosent work, it spams the ui
What calls GoldRush()? What does GameEnd() do? What do you mean by "spams the UI"?
An animation event calls GoldRush() GameEnd() reloads the scene and spams the ui just keep showing the ui and not reloading t he scene.
Show some !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
aight
using UnityEngine;
public class GameRush : MonoBehaviour
{
public void GoldRush ()
{
FindObjectOfType<GameManager>().GameEnd();
}
}```
```cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
float WaitRestart = 0.5f;
public GameObject completeUI;
public GameObject goldRushUI;
public void CompleteLevel()
{
if (SceneManager.GetActiveScene().buildIndex == 7)
{
goldRushUI.SetActive(true);
}
else
completeUI.SetActive(true);
}
public void GameEnd()
{
if (gameHasEnded)
{
gameHasEnded = true;
Debug.Log("GAME OVER!!!!!");
Invoke("Restart", WaitRestart);
}
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Do you get the "Game over" log?
yes it also works in other scenes when OnCollisionEnter calls GameEnd()
Is this object destroyed or deactivated before WaitRestart amount of time has passed? Try putting a log in Restart and see if it's called
nah isnt called.
Oh i fixed iti
instead of calling game end and progressing to Restart()
i just called the SceneManager function in the animation event script
works just fine!
thanks for your help @polar acorn !
<3

OH SHIT
IT JUST COMPLETELY BROKE THE GAME MANAGER SCRIPT LOL
glad i could help
https://youtube.com/clip/UgkxbWw2io51bpIYjVU0O1Z8lea1rCQLVkVI?si=0u9yedptRlx6Lb5g would anyone know how to do this where the camera scroll side to side depending on where the mouse is
21 seconds · Clipped by Colin rhodes · Original video "WARNING: SCARIEST GAME IN YEARS | Five Nights at Freddy's - Part 1" by Markiplier
that close to what i want but i more want it to move with the mouse no matter what no really scroll to the right if the mouse is 50 to the right or whatever
just use a first-person type camera.. ignore the "Vertical" (Y) axis and clamp the horizontal (X)..
use a really slow movement multiplier
but the video does seem more like its just a slow scroll animation or something
here let me load up a fnaf game and take a video myself
i can only send a 10MB video here
i had to cut the video short but this should be good enough
oh thats just a simple mouse parallax
like i hope show enough
cause how im gonna learn unity is not by watch learn unity im gonna learn by making a fnaf game
its mouse movement <- -> translated to rotational movement..
^ yea, its probably pretty simple with cinemachine
has clamps and stuff built in
it not really like this cause like you can see one half of the office and then when you move to the right you can see more of the right side and less of the left side
ya.. when u turn ur head to the right.. u see less of the left of ur bedroom correct?
yea, its camera rotation..
thats all it is.. paired w/ mouse movement left and right
no its a picture
its a pre-rendered 3d scene...
have u looked into how to do those?
im absolutely clueless on how to deal w/ images and videos like that
maybe put it on a curved mesh? lol
so ur gonna jump str8 into making a fnaf clone?
and that how i somewhat learn GM
you're gonna just have to start googling around
not a very common thing to do i'd imagine
to have a camera move with the mouse?
no, that parts easy
Hey guys, this might sound like a very beginner coding question.
I downloaded a project from Github. And it's giving this error saying this class or namespace doesn't work.
Are .Classes treated in a special way when doing imports?
Perhaps it has to do with where I placed the files I imported?
its just a free-look camera w/ the vertical part ignored.. 🎦
yeah
u can program ur own.. or u can use cinemachine..
just research via google.. pick which method u want and you'll find bazillions of tutorials and resources..
if u get stuck come back
i guess you can just make a fake mouse object and make that follow the mouse? and then make that object a child of the 2D camera
thats how i did it in gamemaker
it was just more like what you said at first
how do I fix this issue?
!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.
Hi, before I start, please @ me when replying because I am likely to fall a sleep before seeing your answer, thanks.
I am trying to create a data type that can be serialized in json.
It's working well so far, with one exception.
If I don't inherit from anything, it can't be null.
If I inherit from UnityEngine.Object, json utility never fills it with data(ig it's incompatible?).
If I use ScriptableObject it requires me to create an actual instance of that so, no thanks.
Is there an alternative I am missing?
I explicitly need the object to be null by default and also be able to get a value from the json utility.
Thanks in advance!
I am tring to make Timers(floats )in sync
no need.. u can control the ortho camera thru script.. no reason to have a "fake" mouse object.. you just move the ortho camera left and right u can read the mouse position easily in the same script as well.. something like:
float normalizedMouseX = (Input.mousePosition.x / Screen.width) - 0.5f; // normalized mouse position (-0.5 to +0.5)
i will show video
and this code would go in the camrea 2D unless im dumb which i am
what is a "camera 2d"? .. it can go anywhere (any gameobject).. the script doesn't matter where it is as long as the "Camera" set to Orthographic mode was assigned.. in the script
this is kinda why learning the basics first instead of jumping str8 in makes a difference.. knowing this stuff will just fast-track ur development
the "fun" stuff yakno.
camera 2d is what godot calls the camera and if it a 3D game then its camrea3D
oh, well ur in a Unity discord now.
its taking a long time, so im trying to make a instanced object Practically make another instanced object a certain times in a row and it is not being in sync
use a coroutine
You telling me?
depends on what ur trying to do.. i also am a bit confused on what kinda syncd ur talkin about.. whats not syncing up with what?
these prefabs are not spawning in a synchronized patern
1.5,1.7,1.9,2.1 seconds
code:if (Shooting)
{
if (ShootingTimers[0] < 0f)
{
ShootingTimers[0] = ShootingTimersSet[0];
this.shoot();
}
if(Shooting)
{
ShootingTimers[0] -= 1f * Time.deltaTime;
}
if (Reapeater)
{
if (ShootingTimers[1] < 0f)
{
ShootingTimers[1] = ShootingTimersSet[1];
this.shoot();
}
if (Shooting)
{
ShootingTimers[1] -= 1f * Time.deltaTime;
}
}
if (Gatling)
{
if (ShootingTimers[1] < 0f)
{
ShootingTimers[1] = ShootingTimersSet[1];
this.shoot();
}
if (Shooting)
{
ShootingTimers[1] -= 1f * Time.deltaTime;
}
if (ShootingTimers[2] < 0f)
{
ShootingTimers[2] = ShootingTimersSet[2];
this.shoot();
}
if (Shooting)
{
ShootingTimers[2] -= 1f * Time.deltaTime;
}
if (ShootingTimers[3] < 0f)
{
ShootingTimers[3] = ShootingTimersSet[3];
this.shoot();
}
if (Shooting)
{
ShootingTimers[3] -= 1f * Time.deltaTime;
}
}
}
i guess and TBH i dont need to make this game in unity i already did in game maker and want to switch so I was gonna remake it
so i can learn unity
lol.. ur code makes me chuckle
me?
ive not seen anything like that in a while.
oh i didnt see the long messages
you haven't shared any code..
that what i was think i was like maybe you know me cause i know a spawn
!code. use this to format ur code btw 👇
📃 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
helps make it readible for everyone *including those on mobile)
so each shooting timer index represents a certain timer?
yes
why not do this in a loop? ```cs
if (Shooting)
{
for (int i = 0; i < ShootingTimers.Length; i++)
{
if (ShootingTimers[i] < 0f)
{
ShootingTimers[i] = ShootingTimersSet[i];
this.shoot();
}
ShootingTimers[i] -= Time.deltaTime;
}
}```
i did that
the same thing happen
its just cleaner.. than what u had..
i still think u should try to use coroutines for something like this..
thank you
im trying to think how u could do this w/ coroutines..
what all fire-rates do u have?
and do u have like single-fire, repeater (im assuming semi-automatic, and then full-auto, Gatling)?
4 shots is gatling
nah, u could do the same in deltaTime.. coroutines are nice and readible and easier to work w/ if theres other delays u need to deal w/ eventually
all opinion tho..
does OVRInput work anymore or is it deprecated?
i do a tickmanager w/ coroutines so im biased i guess..
just FYI, this doesn't account for extra long frames causing extra time to accumulate. a timer with a float you increment by deltaTime would account for those longer frames or even potential hangups so multiple ticks can be processed at once in those cases
WaitForSeconds is still dependent on frame time because it's processed at specific parts of the frame. deltaTime counters also experience this. I like to do this to sort of solve that:
public void Update() //can optionally be a coroutine with a while loop, either works
{
timer += Time.deltaTime;
while(timer >= timerThreshold)
{
timer -= timerThreshold;
TimerAction?.Invoke();
}
}
aye ya, i didnt even think about that for some reason lol
mine are UnityEvents
my AI brains AddListener for it
just a generic standin for any event or action
basically just "whatever you want to do each time the timer reaches the threshold"
using WaitForSeconds is limited as you can't check anything within the time you wait. using deltaTime allows you to do that . . .
it's not MonoBehaviour.Invoke, it's how you raise an event or invoke a delegate
it's for events and delegates which are just in c#, not unity specific
there is also UnityEvent which is similar and has its own Invoke method too, though it's not technically an event
you'll use that a lot. it's very handy . . .
there's documentation pinned in #🖱️┃input-system to learn how to use it
also those are events
there's no "optimal" way to use the input system, there are also like half a dozen ways to use it, just use whichever is most comfortable to you and fits your needs best
i wouldn't say there is an optimal way; it depends how you build your project. most use UnityEvents and setup everything in the editor or C# events and do their setup in code/scripts . . .
how would i begin scripting?
some people still poll the input in Update even though they can just receive the input as an event. . .
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i just feel like unity learn isnt helping
then try tutorials on YouTube. that's really it. just make sure to learn C# basics. without that, anythnig will be difficult . . .
ok thanks
make sure you put everything into practice. when you learn or follow something, repeat what you just learned without looking at the material to see how much you remember. while learning or watching a video, make sure you understand every line of code you write before moving onto the next one . . .
I know the way I use it!
it must be the optimal one 😉
I like to use InputActionReference to directly refer to specific input actions wherever I need to receive input
I do use those callbacks.
e.g.
public override void Enter()
{
base.Enter();
interactActionReference.action.performed += Interact;
commandActionReference.action.performed += Command;
// more stuff
}
I have an InputManager singleton that turns action maps on and off based on the current game state
e.g. it turns on humanoid-specific actions if you're controlling a humanoid character
u could have it track the player via code so rotation isnt a factor
because it rotates with the Player too
have u checked the asset store or looked to see how unity's third person character does it
may be something enlightening
one of my camera modes is an orbiting camera that doesn't rotate with the player
it just defines the radius you get at various elevations
I often make it narrow at the bottom and top, and make it wider in the middle
anyway, yeah, I use a Cinemachine Third Person follow component
use a sphere and stick a camera to it (mimic the players up direction for the camera so it doesnt spin)
😛
and a Cinemachine Same As Follow Target for the rotation control (I need to replace that)
It follows an object on the player that's being rotated by a script to have a consistent rotation, even as the player rotates
basically just
public override void Look(Quaternion rotation)
{
Look(entity.transform.position + Vector3.up * 1.5f + rotation * (10 * Vector3.forward));
desiredLookRotation = rotation;
thirdPersonRoot.transform.rotation = rotation;
}
the other Look method does some more work that's not important here
no clue, i typically only work w/ first person and top down (3/4) views
i thought the 3 orbit thing was just how its done
(i am popping out for the night, btw)
who wanna play test my game??
Can someone explain to my how to access the Array in the Physics.OverlapBox Funtion? What i tried
private bool isOnPlant() {
if (Physics2D.OverlapBox(new Vector 3(Position),new Vector2(WaterSize),0,WaterLayer,)) {
currentPlant = results[0].gameObject.GetComponent<PlantLogic>(); //// This One
Debug.Log("Is On Plant");
return true;
}
return false;
}
Weird that the 2D version doesn't have the usual code samples. Check out the 3D version of the function- Should be more or less the same gist.
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
That's what is was looking for, Thank you
hmm then why are you using Physics2D in your code.
If you can let the instance of prefab player in the scene, just refer to it and let it in scene.
If you need that no player is in scene at awake, then instantiate it via _myPlayer = Instantiate(prefabPlayer), this way you are refering to the instance and not pointing to the prefab itself.
I have a small problem, I'm trying to make a script that allows me to switch scenes with buttons. The thing is I have three screens I want to change to, this is for a UI assignment.
This is my current code:
{
public void SwitchScene()
{
SceneManager.GetActiveScene()=op;
if (op == 0)
{
SceneManager.LoadScene(1);
}
else if (op == 1)
{
SceneManager.LoadScene(2);
}
else
{
SceneManager.LoadScene(0);
}
}
}```
I'm 100% sure this is wrong, but I've been at it already for a good 30 minutes now
why does the same line of code not work in different scripts?
what does the error message say
You would know if you hover over the bold red squiggly lines which explain in detail what the issue is
I would put my money on that you forgot to include the namespace.
Do I try to get the active scene, convert that to an integer and then try to put it back in?
Also:
- Don't use
Findtype methods. If you want the Player, then either reference the player component through the inspector or make it a singleton. Awakeis for assignment of values.Startis for invoking behaviour. Move the Player grab toAwake.
What is the issue?
Is this just a general "is this okay?" question, or..?
You mention it's wrong
But why is it wrong? Is there an error? Does it not work?
If you want to be helped you should post all the context, not just parts
Assets\Scripts\SceneManager.cs(17,18): error CS0103: The name 'op' does not exist in the current context
That is the entire script
Well, seems clear enough?
You try to assign the current value of op to SceneManager.GetActiveScene()
There are multiple things wrong here
I suggest you take a good look at the code. I would prefer you learn this yourself rather than spoonfeeding the answer
Yeah, I thought that as well, I wanted to get the value of the current scene, and then have some sort of increment that changes the scene, but I didn't know how to achieve that
You can simplify it by doing something like
var numScenes = SceneManager.sceneCountInBuildSettings;
var currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
var nextSceneIndex = (currentSceneIndex + 1) % numScenes;
SceneManager.LoadScene(nextSceneIndex);
}
And there we go. Somebody proceeds to completely spoonfeed the answer rather than help you learn how to write better code
were you able to solve it , if so what was the problem, just wondering.
You're very close, but the assignment of op is completely wrong
For beginners, the variable is not defined
You have also switched the order. You should assign op and not SceneManager.GetActiveScene()
Sorry if I hurt your ego
Alrighty then
It has absolutely nothing to do with ego. Spoonfeeding answers is the worst way to help beginners
I did manage to solve it with Visual Studio Code quick fix, and I needed to qualify which Vector3 I am talking about, the System.Numerics. or UnityEngine.
so now it looks like transform.position = UnityEngine.Vector3.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
yep, i was pretty sure you had the other namespace imported as well
in generel you won´t need it, get rid of the System.Numerics
i am just confused why it would perfectly work in the other script but not in this one
The issue here is that you have also imported the System.Numerics namespace on the top of your file. You don't need that so you can remove it
Unity has its own numerics system. System.Numerics is .NET's build in numerics
The issue is they both have Vector3 structs
Alternatively if you do end up having two classes with the same name, you can for example also put this on the top of the file:
using Vector3 = System.Numerics.Vector3;
A good example is the Random class. It exists in both UnityEngine and System
So would defining op as an int fix that issue?
ooh thank you, i get it now. is importing different namespaces an advanced scripting thing?
Yes, that's the first issue. Do that and you'll probably fix the second issue
just read what FusedQ said.
Ambiguity errors are common so it's worth to mention you have multiple fixes here
Your solution of specifying the full path is the ugliest one imo
{
int op;
op = SceneManager.GetActiveScene().buildindex;
if (op == 0)
{
SceneManager.LoadScene(1);
}
else if (op == 1)
{
SceneManager.LoadScene(2);
}
else
{
SceneManager.LoadScene(0);
}
}```
This is how it looks now, but I get a new error
Assets\Scripts\SceneManager.cs(13,44): error CS1061: 'Scene' does not contain a definition for 'buildindex' and no accessible extension method 'buildindex' accepting a first argument of type 'Scene' could be found (are you missing a using directive or an assembly reference?)
How would I define the build index?
Looks good, but you can specify op on a single line.
-int op;
-op = ...
+int op = ...
if you have the same Class within 2 namespaces, then you have to define which one you want to use. in your case you have 2 namespaces the one form unity and the one from System.Numerics. Because both of them have Vector3 inside. If you compare both scripts one of them should have System.Numerics the other not.
Actually yeah, let me try strings instead
Where are these errors? In the Unity console?
wait no, that won't work
Let me revert my statement 😄 I was reading too fast, my bad.
You just misstyped buildIndex
which leads to the assumption, that you should check 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
• :question: Other/None
My thought exactly
omg I did
I get the feeling your editor is not configured. It would help you with these things
yeh, but your code editor would have told you
Does the editor help you with auto completion of the member? Please note you should really configure it
These things are trivial in that case
I guess I haven't had it configured
Go ahead and do that. It will help you greatly. Check the bot link below Twentacle's message
It does sometimes, with some things it auto completes, and other phrases not really
It probably works for .NET features in general. It doesn't know about Unity features yet
Alrighty then, I'll check it out and configure it when I have the time
But anyways thanks for the help
The time you save doing it asap will be compensated 😉 😄
my unit does not want to go into the attack state I have scripts that decide these states and an attack controller that references these scripts but now all of the sudden after i have changed nothing he doesn't want to go to the attack state I can see it through the animator tab the transitions are the same to when it worked beforehand
Please share the related !code.
Also, make sure there are no errors
📃 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 suggest you check if your methods are called, first of all
can you join our call because theres a lot of scripts and states and coliders
Nope
If you can't figure out the related code then I suggest you start with checking if the methods are called
Check for actual proof, for example by placing a Debug.Log at the start of methods and at different steps.
the methods are called the debugs say so
Assuming that you have existing debug logging it should point out that it invokes all the behavior and also invokes the attack state
Does it go all the way to the invoke to set the attack state?
it doesn't move into the attack state
theres 5 scirpts should i send them all
Upload those, where your debugging logs stop to work
5 different scripts that set the attack state?
Why not a single place?
there 1 that controls the state and one that iniciates the collider contact and then there 3 other one handeling the states

