#💻┃code-beginner
1 messages · Page 703 of 1
You go the same route as a regular singleton in c#, except instead of creating a new instance, you load it. There should be a few tutorials out there online exactly for this
is there a way to avoid what they'd probably call drilling when passiing functions to other scripts?
i have a PlayerStats script and there is a TakeDamage method there
and i need to call that method inside the enemy attack state script
and for that to work i have to first call the enemy state machine, over there make a public field for the player state machine assign it in the inspector, call it, make a field to initialize the player stats script there call it and then call the take damage function, that can not be the easiest way to do this lol
StateMachine.playerStateMachine.playerStats.TakeDamage(attackDamage);
Why does a state machine have a reference to the player state. Why does the player state machine have a reference to the player stats? It feels wrong on many levels.
And where is that code called from?
that's a lot of code i need to show in order to explain it😅 what's the norm for showing long code here again
using UnityEngine;
public abstract class PlayerState
{
protected PlayerStateMachine StateMachine;
protected Animator Animator;
protected PlayerStats PlayerStats;
public PlayerState(PlayerStateMachine stateMachine)
{
StateMachine = stateMachine;
Animator = stateMachine.GetComponentInChildren<Animator>();
PlayerStats = stateMachine.GetComponent<PlayerStats>();
}
public abstract void Enter();
public abstract void Update();
public abstract void Exit();
}
but this is the player state script
it's a blue print for every state i make for the player
State machines need to be as generic as possible, not caring about where, when and how they are used at all.
using UnityEngine;
public class PlayerStateMachine : MonoBehaviour
{
[Header("Current State")]
[SerializeField] private PlayerState currentState;
public PlayerStats playerStats;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
currentState = new PlayerMoveState(this); // Initialize with a default state
currentState?.Enter();
}
// Update is called once per frame
void Update()
{
currentState?.Update();
}
// Method to change the current state
public void ChangeState(PlayerState newState)
{
currentState?.Exit(); // Exit the current state
currentState = newState; // Set the new state
currentState?.Enter(); // Enter the new state
}
}
and the state machine handles the states
is that not what i did?
Why is there a class specifically for PlayerStateMachine how is it different from the enemy. Ideally, use the same state machine by all characters in the game, whether they are players or npcs.
how would the transitions work tho?
because on the player state machine i call the move state as default
using UnityEngine;
public class EnemyStateMachine : MonoBehaviour
{
[Header("Current State")]
[SerializeField] private EnemyState currentState;
[SerializeField] public PlayerStateMachine playerStateMachine;
public Transform [] patrolPoints;
public Transform playerPosition;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
currentState = new EnemyPatrolState(this); // Initialize with a default state
currentState?.Enter();
}
// Update is called once per frame
void Update()
{
currentState?.Update();
}
// Method to change the current state
public void ChangeState(EnemyState newState)
{
currentState?.Exit(); // Exit the current state
currentState = newState; // Set the new state
currentState?.Enter(); // Enter the new state
}
}
while here i call the patrol state on default
This feels very weird. It's unclear who owns what and what "component" in the system is where in the dependency chain. State machine would usually be on top living directly on the character or some other object that updates it. States should definitely not hold onto state machines as fields. At best they could be provided with it in the methods that the sm calls on these states.
are you saying i studied it all wrong then😭
i spent so much time..
they said you need a blue print for each state
Hi!
I'm having an UI Element with buttons, that instantiates an object, depending on their index and attaches said object to my mouse cursor.
What I want to do now, is hover that object over other objects and press left click in the trigger zones (that works fine so far!). What I do need help now, is, how can I swap two gameobjects? My trigger zones contains an object, that showcases the outline of an object which could be placed there, but when i left click on that object i want to delete the placeholder and place the object I have on my mouse! (I do know how to destroy the placeholder object :D)
Sorry for itnerrupting you gyus btw
Ideally, you should handle the transition in the SM itself, not from outside of it. The SM could query the current state transition, and when the conditions are right, activate that transition.
wait im not doing that??
public void ChangeState(EnemyState newState)
{
currentState?.Exit(); // Exit the current state
currentState = newState; // Set the new state
currentState?.Enter(); // Enter the new state
}
doesnt this do that
and then i conditionally call the change state method:
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UIElements;
public class EnemyPatrolState : EnemyState
{
public EnemyPatrolState(EnemyStateMachine stateMachine) : base(stateMachine) { }
NavMeshAgent agent;
int nextDestinationPoint = 0;
public override void Enter()
{
agent = StateMachine.GetComponent<NavMeshAgent>();
}
public override void Update()
{
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance && agent.velocity.sqrMagnitude == 0f)
{
{
nextDestinationPoint = (nextDestinationPoint + 1) % StateMachine.patrolPoints.Length;
agent.SetDestination(StateMachine.patrolPoints[nextDestinationPoint].position);
}
}
if (Vector3.Distance(agent.transform.position, StateMachine.playerPosition.position) < 10)
StateMachine.ChangeState(new EnemyChaseState(StateMachine));
Animator.SetBool("Walking", true);
}
public override void Exit()
{
}
}
in the individual states
Anyways, back to your original problem.
- You should make a TakeDamage method in the character class(ideally shared for all characters, player or not). Then call character.TakeDamage when youwant to apply damage to a character. The logic of calling the same method in stats should be handled internally to the character.
- Provide a reference of the character to whoever needs to deal damage to it, instead of letting it get it via a convoluted chain of references.
Might want to start a thread and provide more details there. Maybe in #1390346827005431951 so that your post is not lost.
yes but the problem is the enemyAttackState is not attached to any game object and is not a monobehaviour so i can't directly assign things to it
it's only being called by the state machine
that's the only way it runs
Of course you can. And should be. You can pass data to it in the constructor or some kind of initialization method. For such a state to work properly it would obviously need to know what it's attacking.
omg right the constructor!
basically like i do here right?
using UnityEngine;
public abstract class PlayerState
{
protected PlayerStateMachine StateMachine;
protected Animator Animator;
protected PlayerStats PlayerStats;
public PlayerState(PlayerStateMachine stateMachine)
{
StateMachine = stateMachine;
Animator = stateMachine.GetComponentInChildren<Animator>();
PlayerStats = stateMachine.GetComponent<PlayerStats>();
}
public abstract void Enter();
public abstract void Update();
public abstract void Exit();
}
passing the animator and playerStats
wait is it good to do that tho if not all state need it?
That's still not ideal. First of all, I'd avoid passing a character stats around at all. It should be data internal to the character and nothing else should be messing with it.
It depends. If using a context, it's gonna contain a lot of data that not everything needs.
i think that script is not properly named tbh haha it just holds a lot of functions😅
oof it's too long to send
// Method to handle player death
private void Die()
{
Debug.Log("Player has died.");
// Here you can add logic for player death, like respawning or ending the game
}
public int GetCurrentStamina()
{
return currentStamina;
}
// Method to restore health
public void RestoreHealth(int amount)
{
if (currentHealth >= maxHealth)
{
currentHealth = maxHealth; // Cap health at 100
return;
}
currentHealth += amount;
PlayerUI.SetHealth(currentHealth);
}
for example
from PlayerStats
// Method to take damage
public void TakeDamage(int amount)
{
currentHealth -= amount;
PlayerUI.SetHealth(currentHealth);
if (currentHealth <= 0)
{
currentHealth = 0;
Die();
return;
}
}
// Method to use stamina
public void UseStamina(int amount)
{
currentStamina -= amount;
if (currentStamina < 0)
currentStamina = 0; // Prevent stamina from going below 0
PlayerUI.SetStamina(currentStamina);
lastStaminaUseTime = Time.time; // Record the time when stamina was last used
}
I mean, there are many issues I can point out. But I feel like at this point it would mean rewriting most of your project.
should i transfer all this logic somewhere else?
or is only the name of the script misleading
i think this mess happened because i discovered state machines only after doing all of this haha
Player stats should deal with player stats. There shouldn't be "die" and similar methods that are related to the character as a whole, not just it's stats. "Die" in the context of stats is just setting health to 0. Nothing less, nothing more.
Rather than naming issues, you're mixing the responsibility of your components(not unity components).
i only did that because i initiazlied all the variables in the same script😅
[Header("Player's Movement")]
public float walkSpeed = 5f;
public float runSpeed = 10f;
public float crouchSpeed = 3f;
[Header("Player's Forces")]
public float gravity = 10f;
public float jumpForce = 5f;
public Vector3 velocity;
[Header("Player's health")]
private int maxHealth = 100;
private int currentHealth;
[Header("Player's stamina")]
private int maxStamina = 100;
private int currentStamina;
private float lastStaminaUseTime;
private float StaminaRegenerationRateTimer;
[Header("Player's UI")]
public PlayerUI PlayerUI;
[Header("Mouse")]
public float mouseSensitivity = 2f;
public float lookLimit = 45f;
public float rotationX = 0f;
so i said might as well make the methods here to access them
Accessing a stat is fine. It's part of the stats object responsibility
i meant accessing easily in the same script haha
Ah, right it's called player state. This is definitely a misleading name especially since you're using it around state machines.
instead of froma different script
nono PlayerStats
i also have a PlayerState
which is this:
using UnityEngine;
public abstract class PlayerState
{
protected PlayerStateMachine StateMachine;
protected Animator Animator;
protected PlayerStats PlayerStats;
public PlayerState(PlayerStateMachine stateMachine)
{
StateMachine = stateMachine;
Animator = stateMachine.GetComponentInChildren<Animator>();
PlayerStats = stateMachine.GetComponent<PlayerStats>();
}
public abstract void Enter();
public abstract void Update();
public abstract void Exit();
}
this one is clean haha
Why is it a state even? What does it represent logically? Can a character transition into or out of it? So, like can a player become an enemy?
no this is the blue print for every player state
its all abstract
which from my understanding forces every script inhereting from it to have these methods
while also being able to pass it thigns via the constructor
Then maybe a StateDefinition or something is a more appropriate name. But then again, I'm not sure why you need it in the first place.
thats true haha
could you share where you learned state machines i might be overcomplicating it😅
i learned it from a few videos
i was lost at first too
It has less to do with state machines and more with OOP principles, like single responsibility and encapsulation.
A state machine is really just a a system that switches between states. Everything else is an extra.
hmm so it's more about C# than Unity?
Not C# even. The same applies to many OOP languages
So if i want to have a greater understanding of it i should look up C# OOP videos?
oh it's handled the same?
Yes.
Yes. It's all logic. Unrelated to how you write it down.
A big part of it comes from experience, but learning the OOP principles can get you started.
i barely ever scratched the surface with that so it will defiitely be helpful!
Sorry for interrupting, can someone help me really quick. I've been trying to make a rocket league type game and ive been trying to make a system where the goal effect color can change depending on which side it lands. But it just refuses to change color
!code but also you clearly have errors in console. those could easily be affecting whats happening here
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 just solved them and the particles still dont change color
Is the issue that the color value in code isn't being passed correctly, or is it something with the material that's not working? Try logging the color after you set it. See what value you're setting it to.
I have no idea. Because everylast script has the effect refrence. but every attempt I make to change the color doesn't work. It just stays white.
I don't mean to be annoying but how do i have it log the color
I'm not good at this i'm sorry
Debug.Log
guys so now i wanna see what my main camera prespective looks like but idk how to change it, now my game section i mean the circle sign one its showing backgroundcamera prespective but i want it to show main camera prespective like the arrow one
do you guys know how to change it?
Its not even changing
Drag the scale slider at the top of the game window all the way to the left.
Also consider not using Free Aspect mode and changing it to 16:9.
Another log says I "Don't have access" to the material too. but the material still doesn't change when I put it to shared material
So, what does the log say is the color that you're setting the particle color to
Red
ahh the problem is just the camera deept number thanks for ur help bro 👍
and yeah i've scale it to 16:9
Does it say the word "Red"?
My bad. It says this
Okay, so that's more what I was expecting. This shows you're not using values in the 0-255 space and that your alpha is not 0. Where in the code are you logging it? Send it via !code instead of a video this time
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
I believe you'll need to set the color via the particle system itself, not by accessing the renderer.
https://discussions.unity.com/t/how-do-i-change-particle-system-color-via-script-in-unity-5-6-1f1/188736
The start color of the particle system is just gonna change it as soon as you play it
Thank you. I'm sorry for how i am, Unity is very overwhelming for me
It's very overwhelming at first but you get used to it, the best thing you could do is follow the official Unity tutorials on their website it gives you an incredible base
how do I fix this?
get rid of system.numerics or just manually pick which one you're using by typing out the full name
why do you even have Numerics imported
it was probably a suggestion that you accidentally accepted?
anyone knows why am i still taking damage even tho im not withing the collider?
what this does is calling this script on a specific frame of the enemy's animation and it's calling this overlapSphere function to see what it would collide with and then check if one of them has the player tag
but even when im outside of range that i visualized for debugging it tags me
Have you chucked a debug log in that function
logging what?
That it happened
it all works perfectly the only problem is that i still get hit when above it
you can see the healthbar in the video haha
Means nothing to me
Add logs. If you see it printed twice when it's supposed to be once, look at the callstacks
You claim your still taking damage even though your not in the collider
that means
A. you are in the collider
B. something else is giving you damage
C. some other weird thing etc.
you need to narrow down what exactly is happening in order to determine why it should or shouldn't be happening
i see, lemme see what i could add
could the size of that sphere be off even if i pass it directly in the code?
maybe your collider's size is bigger than the actual object?
your a step too ahead here
you add logs to see whats going wrong in the first place
log to see if the sphere check is even running ^
ohh
oh does that not check for null?
it's a weird unity quirk-ish
oops haha
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Object.html
The null-conditional operator (?.) and the null-coalescing operator (??) are not supported with Unity Objects because they cannot be overridden to treat detached objects objects the same as null. It is only safe to use those operators in your scripts if there is certainty that the objects being checked are never in a detached state.
just dont use that ? syntax on UnityObjects (monobehaviours, scriptableobjects etc.)
it's a relatively niche thing and easy to not know
oh god i gotta change it in so many places XD
it seems the docs were updated because it never stated when its safe to use before, although it was already kinda obvious
i used it in the state machines too😭
but either way I wouldnt use it because you could think its safe while its not, leading to hard issues to debug. for consistency sake too
easy to fix in a little bit
well you literally just dont need it in some of those cases. How is your currentState ever null when its private and immediately set on Start?
this is literally not possible to be null
Is currentState even a MonoBehaviour or unity Object?
If not, then it's fine to use ?
how is this for logs?
A little much but more is better than less
check the problem and see what logs run or dont run
ohh it's not
!code also, this is a pain to copy for writing examples
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
all passed
is that what should happen
yup! the script runs it hits all nearby objects
finds the one with the player tag
and gives it damage
did the problem occur
is that what should happen
and only these logs when running away from it
so the problem seems to be only vertical
nope you should be able to outjump it
vertically
Good morning everyone
I mean more literally
and it even takes the max verticality correctly 1.5
new Nooby question 🙂
Imo its also pretty bad to throw in checks everywhere just to avoid errors. Ill use the state machine as the example but this applies to everything. in your state machine, do you explicitly want to allow a null state where an enemy cannot do anything? this seems like the game would be in a broken state if this was possible, yet your code would not notify you of this when testing because theres no error
you tested scenario 1: not jumping, logs reflect intended behaviour
you tested scenario 2: jumping, do logs reflect intended behaviour?
the thing with this kinda issue is it doesn't really "matter" what the code is actually doing, it's narrowing down if the code is doing what your want it to do or not
Your either failing to tell it to do the right thing or your succeeding in telling it to do the wrong thing
I have added these to a sprite of a space station that im trying to make collision detection for a space ship but its not working and my spaceship just flies right over the top :s. Ive watch a bunch of vids and looks on forums but im missing something still
ohhh wait it wouldnt give me a null error??
sorry im sure this is simple to you guys but i just cant seem to see what ive missed
errors are good
omg right cuz im not assigning anything in the inspector XD
yea but this would be a silent one hahaha
if something needs to not be null hiding the problem away with a null check doesnt fix it
sometimes the cars gotta crash if its broken
Of course not, youre checking if its null using ?.
Which wont call the function if it is null
ill just remove them haha, but any ideas for the sphere?😅
again you gotta look at your logs
does the spaceship also have a rigidbody
whats happening that shouldnt be happening
whats not happening that should be happening
i mean this code wise
but it's all perfect from the logs🥲
ye this is what i have for the spaceship
what does that mean
You said it yourself, its not working when vertical. How is it perfect from the logs if logs are printing when they shouldn't
that it's all giving the values im expecting
because it gives the max value 1.5
vertically
Debug.Log($"Y difference to shockwave: {yDifference}, max allowed: {maxHeight}");
I am waiting for bros pfp load😭
is there no different way to do this btw
like just using the on collider enter🥲
or is it not possible with the OverlapSphere
try to delete the rigidbody from the space station maybe, i didnt really do 2D physics stuff before😅
The spaceship also needs a collider. If it has one, then you'd probably want to show how its moving
Im not sure what you mean by i want to show how its moving ? do you mean you want to see the script?
i think he means like literally how it's moving in the game
that you said it wont collide
The script yes, but first does it have a collider?
you nailed it the ship needed a collidor
oh lol
its working now thank you
can you add more than one collider to sprites?
as i want the space station to have docking areas but i need a collider with a trigger to run a script right?
also is there a way of only seeing the spaceship so i can adjust the collider without all the busyness on the screen?
select it, then press shift + h
also if you want the icons there removed, you can temporarily turn off gizmos at the top right above the scene view
How do I fix this...?
conditions dont use ;
you and my friend responded at like the same time
Im just dumb...
Brill thank you
except switch expression and ternaries
i mean those aren't exactly exceptions, just different contexts
it's not that conditions don't use ;
it's that control flow statements take 1 statement and a ; can serve as that statement
not a code question, #💻┃unity-talk
ok sorry
is the character controllers isGrounded check essentially useless or do I just not know how to use it?
it would be beneficial if you describe what issues you are having with it
make sure you move down with gravity every frame
the isGrounded check basically checks if it hit the ground, not if it's currently near the ground
so if you don't apply gravity, it's basically hovering 0 units above the ground and not actually on it
hmmm okay, thanks for the tip
rn i only have gravity applied if !isGrounded
ill try it out
But yes, many people use alternative solutions to this, either doing a raycast down or a spherecast at the feet of the player
I'd avoid using character controller at all.
im guessing spherecast is superior to raycast here? in that a raycast would return not_grounded when youre standing off an edge
yes, in that case it would be better, really depends on your game
which one is "superior" depends on your intent and the possible level layout
if you have a flat world and you just want to check if you can jump again a raycast is fine, if you have edges your suspicion is right
the animator is being hard on me for a 3d character
did u say please?
This is a code channel. If you need help with animation, then use #🏃┃animation
my little smooth brain cant understand what Im supposed to do...
You have declared InputDirection in a different scope than where you're using it
Also, local variables should be camelCase, not PascalCase
...what does that mean...?
You need to learn C# basics.
yeah but Im doing this for a game jam so I dont really have timeeeeeee
so you are making a game without knowing how to make one
Why are you doing a game jam without knowing basics..?
Im learning as I go
it worked before
Then take your time
I was in another game jam before and it turned out well
Well it doesn't seem so.
This is the tutorial
Im pretty sure I have the same thing as it
So I don’t know why mine isn’t working
You don't
The pm is because they were talking GetSlipeMoveDirection from the PlayerMovement script but I just coded the Slide in the PlayerMovement script from the start
I don’t know if that messed it up or not
can you show the whole script as code
I can show my code but not the video
yeah, that
The whole script or just the part Im talking about?
The whole script is like 300 lines so I don’t think it’ll fit in a discord message
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
this doesn´t help, it is missing the important part you are talking about
It is…?
just use a code bin
Presumably because you failed to paste it between the backticks. Use a paste site instead.
Every time I click copy and paste it puts it as a .txt
use a paste site instead
how do I do that...?
I've already pointed out the problem and linked a resource, but it seems to be ignored in favour of this 
The code in the magenta scope has no idea about the code in the blue scope
so how do I make them know about eachother...?
You don't
You declare things in an outer scope if two inner scopes need to use them. As the code in your tutorial has done
I think Im just blind because I literally do not see any difference between the tutorial and my code
You click save and copy the new url
Besides the pm
The website url?
How do you think are these even remotely similar
does the pm thing really matter...?
I thought that if I just put all the code in the folder it was reffering to I wouldnt have to deal with that
the other line
you are not blind you just have to read what people and the dyno bot post
and before diving into game dev, at least learn a few basics of c#
Hmm…. This is the toughest game of spot the difference ever…
Now I really dont know the difference
{
if (!OnSlope() || rb.linearVelocity.y > -0.1f)
{
rb.AddForce(InputDirection.normalized * SlideForce, ForceMode.Force);
}
else
{
rb.AddForce(GetSlopeMoveDirection(InputDirection) * SlideForce, ForceMode.Force);
}
}```
really only difference I see is the pm.
And now what's the error
I'm using the ColorCurves class in a Volume, to change the look of my game.
It all works well when configuring the TextureCurve from the editor. But I just can't understand how to configure it from code. Any ideas?
Edit: nvm sorted it
The name 'InputDirection' does not exist in the current context
And where is it declared
int x;
This is a variable declaration
All your variables need them
Where is that done for InputDirection?
Now you just removed the Vector3 InputDirection = ... line instead of moving it in the right place
look at the tutorial, find where it is there, and put it in the same place
it isnt...
Sounds like a problem!
maybe thats the problem...
And hence that's why it says it doesn't exist
because it doesnt!
guys i have a problem that do not print my text in unity's console.
is that component attached to a gameobject in the scene
they're passing a string variable
This makes sense
You have to have it attached to something in the scene
*in the scene, not just in the project
hence why i specified "in the scene" in my question
so what should i do to fix it?
I forget vocabulary
Put the script on an empty or a cube in the scene
I think that would work
you should consider going through the pathways on the unity !learn site to actually learn how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Now Im even more confused
I don’t have any errors but the thing it’s supposed to do isn’t happening
its supposed to make it where when you slide down a slope it doesnt do this wierd bouncy thing
but its still doing it
{
if (!OnSlope() || rb.linearVelocity.y > -0.1f)
{
rb.AddForce(InputDirection.normalized * SlideForce, ForceMode.Force);
}
else
{
rb.AddForce(GetSlopeMoveDirection(InputDirection) * SlideForce, ForceMode.Force);
}
}```
what difference
The only difference I see is the timer which Im 99% sure is optional and the pm. which I dont think I need
because pm. refers to the PlayerMovement script because the tutorial used two seperate scripts but I just put the slide code in the PlayerMovement script because I didnt think it would change anything
debug some values and check the flow to make sure it's what you expect
I have no idea what that means Im sorry 😭
I am very bad at vocab
what IDE are you using?
Visual Studio Code?
!vscode
set it up properly and then you can attach the debugger to unity
so you can see values of variables in real-time
looks configured to me, what are you seeing that says it's not configured? 🤨
was just a general note, if he has never debugged theres a good chance that isnt set up
you can look at the token highlighting to see if it's configured or not, it seems configured already.
im not familiar with vscode, so no idea
just wasnt sure if highlighting is maybe working by default
and yeah im using rider, so neither familiar vs nor vsc 😄
i can't actually find examples of unconfigured rider in this server lmao
cause rider brings plugins by default, its basically made to use with unity 😄
yeah its configured, but for whatever reason it always just immediately fails the second I click debug even though everything is set up the exact way all of the tutorials do...
no it's for .NET
now, yes, it started as an IDE for gamedev
what do you mean with "it fails"?
you could also just use Debug.Log to check stuff
it's less flexible but less setup
it just stops and says Failed to attach debugger at 127.0.0.1:56516
I got a debug session earlier
but its just breaking now
also a video or something would be good to see what it does rn, "this weird bouncy thing" sounds ominous 😄
A tool for sharing your source code with the world!
how would i implement a 1 second cooldown to using this coroutine
my brain aint working rn
wait Ill turn it into an mp4
several ways
- set a timer that ticks down
- set a variable that you reset after some time
and there are several ways to do either of those as well
it's [mask](link) or [mask](link "hover text"), btw
yeah i typed something and then pasted that over it, instead of pasting over it converted the old text to a link title 😄
"new" function of discord
its supposed to go smooth down the slope
the guy in the tutorial said it supposed to do the bouncy thing and gave the fix but I implemented the fix and its still doing it 😞
oh yeah i could just add another wait for seconds at the end
whoops
thanks
there is so many discord things i would want to turn off 😄
hey everyone, im trying to make a 3d movement system and i almost have it working my only problem is when walking or jumping into the side of an object the player physics doesnt work very well as it will float or not move side to side. to fix this i added a physics material that removed friction from the block and this worked great but i only want it to affect the side of the object and not the top so i can still walk on it fine. or if someone thinks there is a better way of doing it the please lmk, thank you in advance.
Everytime I commit to my branch on github then another person merges, it always causes merge conflicts n blows up the repo, is this a common problem in game dev or is this my issue?
sounds like you're modifying the same files at the same time which is usually something you'd want to avoid. but you should also make sure you set up your repo to use unity's unityyamlmerge tool to help with handling merging yaml files (like scenes and prefabs)
#1157336089242112090 would be the right location to post about version control related issues though
Merge conflicted scenes can sometimes be merged manually but often not so making use of prefabs more helps
Would making backup prefabs and working on those be a better move?
I have done this before where I make a duplicate, pull changes, resolve using theirs and copy/re do my changes
Just a tip, if you know you are working on 2 parts of one scene, put both parts in a prefab and work on the prefabs, the scene just keeps the reference so it doesnt care about changes in its child prefabs
There is this tool from unity to merge yaml but I never got it to work
yo i added a wait for seconds like u suggested but i want the console to log that its on cooldown for that duration if they do try to roll again an if statement for that is all i need right
before the isRolling = false, your if already checks for that one
ahh yeah
and then under that i can do my if statement right?
your input handling already checks if isRolling is false and doesnt do anything otherwise
yea but lets say the player is trying to roll again but its on cooldown for that 0.5 wait period
yeah the variable turns to false AFTER that 0.5s allowing the player to jump again AFTER it
or do you want to buffer the jump?
so if he presses in that 0.5s he waits until after the cooldown and then jumps?
nah none of that i just want the game to let the player know that they cant roll in that 0.5 period until its done if they do try to do so
a buffer isnt a bad idea tbf
do you want to put out a warning sound / message to the player?
yep
you can do that in the else branch of your input if
alright
unless you only want to show it in the 0.5s, that method i described would output it during the whole jump if the player presses again
like so?
then it would output also if the shift key is not pressed 😄
do else if (isrolling == true) (pseudo code)
Yeah this singular bug that people will barely ever even run into has taken like 2 hours of valuable ass game jam work time so Im just going to move on
rolling being true doesnt necessarily mean that its on cooldown right
because what im doing is just yield waiting 0.5 seconds after ive reset the collider size
it means the player is currently rolling OR its on cooldown
yep
oh then you can work with a new variable that says isRollOnCooldown
you set it to true before the 0.5s wait, and false after
could do
but hold on why did u suggest to put the wait for seconds before is rolling = false
should it not be at the end
because in your current version you can roll again once isRolling = false
so it wouldnt wait for the 0.5s
ahh yeah
You can either work with a 2nd variable as I said above or you can implement a simple state system for the roll
basically a variable that contains an enum:
public enum RollState
{
Ready = 0,
InProgress = 1,
OnCooldown = 2
}
void Update()
{ // If roll button is pressed and player isn't already rolling start the roll coroutine
if (Input.GetKeyDown(KeyCode.LeftShift) && playerattributes.rollState != RollState.InProgress)
{
if (playerattributes.rollState == RollState.OnCooldown)
{
// Notify player roll is on cooldown
return;
}
StartCoroutine(Roll());
}
}
private IEnumerator Roll()
{
playerattributes.rollState = RollState.InProgress;
playerattributes.PlayerCollider.size = new Vector2(originalsize.x, originalsize.y / 2);
yield return new WaitForSeconds(playerattributes.RollTimer);
playerattributes.rollState = RollState.OnCooldown;
playerattributes.PlayerCollider.size = originalsize;
yield return new WaitForSeconds(0.5f);
playerattributes.rollState = RollState.Ready;
}
enums are easy to understand, you can see it as "names for numbers" and you store that number in a state property, then you can react on the current state
a boolean with more values 😄
what i did above cant even really be called a state system, its a very very simplified
Hello, can someone help me pls ? I'm my second prototype / learning game, with actual movements in 3D. Getting this error:
Assets/Scripts/InputManager.cs(8,13): error CS0246: The type or namespace name 'PlayerMotor' could not be found (are you missing a using directive or an assembly reference?)
Code:
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
private PlayerInput playerInput;
private PlayerInput.OnFeetActions onFeetActions;
private PlayerMotor motor;
void Awake()
{
playerInput = new PlayerInput();
onFeetActions = playerInput.OnFeet;
motor = GetComponent<PlayerMotor>();
}
void FIxedUpdate()
{
Vector2 input = onFeetActions.Move.ReadValue<Vector2>();
motor.ProcessMove(input);
}
private void onEnable()
{
onFeetActions.Enable();
}
private void onDisable ()
{
onFeetActions.Disable();
}
}
do you have a component called PlayerMotor
also your FixedUpdate, OnEnable and OnDisable methods are capitalized wrong, just as a sidenote
seems like a case of unconfigured !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
ty
I don't understand one thing:
A component is something I "add" in an object, right ? But my script is not linked to anything. SO I need to add the PlayerMotor "in" the script ?
that is a gross misunderstanding of what is going on here. you should stop what you are doing and follow the beginner pathways on the unity !learn site (after you've configured your IDE of course)
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
alright, thank you
What is a PlayerMotor
a component I guess ? xD
You wrote it, what thing were you trying to get when you made a variable of type PlayerMotor?
A script that handles the player movement system ?
And what script would that be
here's a fun fact: the name of the script file has nothing to do with the class inside. your class is not named PlayerMotor
After seeing the other script, i am betting $5 on a capitalization error!
that or it's still named NewBehaviourScript or whatever the default name is
It was my "public class" that was called "NewMonoBehaviourScript". ty guys
C# is so different than other languages
looks like i lost $5 to you 😄
it's really not. even other languages you still need to use the correct names for things
I mean in the logic
logic is the same across all languages because logic does not fundamentally change
😌 😮💨
how to get mouse pointer position like that
for what purpose
i want to make a check if pointer is near boundaries
its usually 0-1 based, not -1 - 1
you just need to convert from screenspace to viewport coordinates
i mean with simple math you can get the other range, but i dont see a reason 😄
but it would give 0-1 not -1 to 1
it wounld not matter
what you want is viewport coords they are 0 to 1 but you can easily remap to -1 to 1 if needed
i did end up implementing the second variable u suggested but i decided there should only be a cd if the player doesnt become grounded during the roll timer wait, how would i implement that?
https://paste.mod.gg/zcfdudnpqihr/0
A tool for sharing your source code with the world!
https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html
And if you really want -1 to 1 you can convert it easy:
value = value * 2 - 1
isGrounded implementation is a whole topic for itself, look into that and if you have trouble you can ask here
Also you will still display the "Roll is on cooldown" right now whenever you havent pressed left shift 😄 cause that fails the if condition
alright cool
changed the statement to this but now whenever i press left shift in the logs i just get the message
yeah because thats what your if does? if leftshift is pressed + the other conditions it prints the message 😄
also for a float, never check if its == or != a specific number
always do greater than or smaller than checks with <, >, <=, >=
oh wait, your last condition will never be false because of what i just wrote, you subtract Time.deltatime from it, you are below 0, not exactly 0
oh so i could just do <= 0
yes
well in the case of the message you want > 0
because you wanna check if there is still some cooldown time left
👍
what are we meant to do for concave colliders on an rb?
I just want a physics enabled bowl lol
you can break the mesh up into multiple smaller colliders
there are also assets in the store that do that for you automatically, not sure if there are any free ones though
not too hard to break up a shape in blender to a bunch of convex ones
you just end up with a lot of edge shapes making up concave curves
You don't. You make multiple convex colliders
im so confused whats wrong with this code 😭
Well first of all you shouldn't add Time.DeltaTime to AddForce
Secondly you are applying 2000 "force" each fixed frame without input meaning your player is moving uncontrollably each fixed frame
It's still moving uncontrollably each frame cause its outside of an input statement
Unless that's intended
and why not?, i know it sounds pathetic but im going off a vid tut and its saying to do that
which video ? the video is wrong
Well the video is wrong
i think i know why
AddForce is already moved on fixed ticks
the time isnt relevant. bad tutorial is a bad tutorial regardless
AddForce already has its own fixed time and you have it in FixedUpdate witch is also fixed time
this is his and its working perfectly fine
another garbage brackys tutorial, what a surprise
problem now is I can't use an icosphere cut into the individual triangles because the unity convex hull conversion needs at least 4 verts :))))))))))))))))))))))))))))
Again its still wrong
whats fixed time
Just a word i used (probably the wrong term) to define that the number of frame you have dont affect the speed
okay i got it
so let me see if i can try and fix this myself
wit hur help obv
idk what im saying
its very simple, just remove Time.deltaTime from all the AddForce calls.. this way the numbers also don't have to be cranked up so high
Hey! I'm using unity's animation rigging package in combination with normal animations. Since im using the rig building I can no more rotate the whole armature in the players local space, how would I go abound replicating the same effect?
mb
what else would be making this not work? (sorry for being a pest im just really new)
you have to explain what "not work" means ?
also the second addforce is going to keep running if D is not pressed
its explaining to you whats wrong, you're using the Old input system but its not enabled in the Player Settings
You'd have to go and switch it to Both, or OLD only, to be able to use Input class
Where can i change that
In Player Settings like it said
i think i found it
I feel like we should get a bot command for that one
Since they changed the default input type it's like 90% of the questions here any more
which one would you recommend,does it matter
Put it on Both for now so you can actually learn that since most tutorials will still have that system
yeah that makes sense
in time you should learn the new input system though, its far better and not that much more difficult
where can i find stuff on it?
the manual / docs and some unity videos they have on !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
there is also this which gives you "conversion" from old to new equivalent methods
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/Migration.html
thanks man, this will not be the last u will be hearing from me
If I use OnTriggerEnter or OnCollisionEnter in a parent object with Rigidbody, does it automatically detect collision on all child objects with colliders?
why not test it out for yourself ?
those colliders become part of the rigidbody so its likely
Just made myself a working tech demo, it’s largely 2D but I want to have a minigame in another scene in a 3D world space. I read it’s possible but I can’t make heads or tails of it, no matter what I do the camera still appears to be in a 2D mode
Don't use an ortho camera
switch it from ortho to perspective
No that’s the first thing I did, no change
also, this is a code channel... if it's not code related, move to #💻┃unity-talk
you changed the actual camera component, and not the scene camera, right?
I appreciate that thank you
May need to double check that
This should be a great resource, I’ll play around with it when I get home. Thanks a million : )
I’ll be sure to post in the right channel if I have issues. Posted in here cause I saw there might be a code component to it
any idea why the removing bit doesn't work? trainLength points to the value that I'm changing, so there definitely are more trainCars than trainLength, yet they're not being removed.
Hey, I am testing Unity 6.3 and noticed that I have to explicitly do this now in order for the default map to be active:
InputSystem.actions.actionMaps[0].Enable();
I am positive this wasn't the case in 6.0, am I mistaken?
Again, it's the default map that should be project wide.
If this is a bug, where should I report it?
nvm I was only calling it when there were less cars 😭
the while here seems pretty unnecessary
also for future reference, !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
pretty sure thats common though
its a small enough snippet that I felt it wasn't needed
also youre right
no that's not a factor at all
it being text just makes it easier to reference
Hi all, I'm looking at building a dynamic bullet impact system, simply put if a bullet/raycast hits a type of object, a certain type of impact/decal is played/placed (at the moment my prototype is using tags), but I need to to also work on a terrain and be dynamic based on the terrain layer the bullet/raycast hits.
Would anyone have any pointers, or a resource (tutorial etc.) on how to achieve such a thing please? I'm not really sure what the search term should be for el goog
I've seen people use the texture / some type of mapping with that to play specific sound based on texture/material (this was for footsteps but I'm sure the same concept applies)
Yeah, that's what I was thinking. The problem is, everything I've found ONLY applies to terrain, and I can't see how to apply it to gameobjects etc.
But, typically, I have just found something from llam academy and seems to look like what I want to do.
A common need in video games, to increase immersion of the player, is to add some effect when an impact is made. Using this system whenever an impact is made by any arbitrary action in your game, you can simply call SurfaceManager.Instance.HandleImpact() and this system will utilize Scriptable Objects to determine which effects to play. This all...
ya tbh its even easier on materials/ gameobjects than terrain so you're covered then, their videos are good so i'm sure that will work well
Yeah, it's looking promising so far.
if i want function A to always listen and execute whenever function B is called, i use events rather than action right?
trying to use event approach as it can be less expensive?
both are the same
events are better because then anything can subscribe to be notified when "event a" happens
events are just a specific use of actions
i have an implmenetation actually
public override void OnNetworkSpawn()
{
InputManager.Instance.EnableControl();
MoveInput += InputManager.Instance.joystickCore.OnDrag;
}
private Action<PointerEventData> MoveInput = (PointerEventData evt) =>
{
Vector2 input = InputManager.Instance.joystickCore.Direction.normalized;
if (input == Vector2.zero)
{
input = InputManager.Instance.playerInput.Player.Move.ReadValue<Vector2>();
}
Debug.Log(input);
};```
u can assume timing has no issue and ignore backend/network stuff, that isnt important here
public event Action MyEvent; 😃
public Action MyShitEvent; 🙁
what theme makes it pink?
and make it public otherwise no one can sub to it 😆
i think i actually messed up then
this is actually "callback"
and now you got a cool Lightning bolt
best reason
how do you mean? events are callbacks
fancy list of function pointers
"calling back" some code through delegate
public void OnDrag(PointerEventData eventData)
{
//use event data (onpointerdown)
}```
you can treat this as void start()
```cs
public override void OnNetworkSpawn()
{
InputManager.Instance.EnableControl();
MoveInput += InputManager.Instance.joystickCore.OnDrag;
}```
```cs
private event Action<PointerEventData> MoveInput = (PointerEventData evt) =>
{
Debug.Log(input);
};```
i still need to invoke moveinput right? even if its registered to OnDrag(), like the debug log inside wont call if i dont make invoke somewhere else?
btw moveinput doesnt even need pointer event data, im making it 1 param only because if i dont do that i cant register action to OnDrag
MoveInput += (PointerEventData evt) => InputManager.Instance.joystickCore.OnDrag(evt);```?
can be the other way too im sure you can figure it out:
event += () => OtherFunc(null);
hi, i'm making a multiplayer game. Currently, I have a time manager script which has public events. It handles the game time and invokes the events at the right time. Right now, there are 8+ events. Lots of different scripts have subscribed to each event. Is this bad practice? If so, is there any alternative?
isnt that high coupling or something (im not sure what its called)
just keep in mind even if the objects are disabled the events still will get called
also coupling will happen, its just controlling where it is
well duh
how do you know its the "right time" you'd wanna test this with multiplayer tools that can simulate long latency
the time manager has a variable for the time, and when a certain amount of time has passed, it invokes an event
most of the events are invoked on the server but some on the client. for the ones on the client, i send a client rpc to invoke them
https://pastecode.io/s/brq9775q
hi, this code works as intended, just looking for a peer review so I can improve if possible. Meant to be a code based alternative to unity's in built animator because I hate its guts.
somehow it works but the action seemed executed 2x more times?
Did you subscribe multiple times?
Subscriptions remain until you unsubscribe manually OR set the whole event to null
public override void OnNetworkSpawn()
{
InputManager.Instance.EnableControl();
MoveInput += () => InputManager.Instance.joystickCore.OnDrag(null);
}
private void Update()
{
MoveInput.Invoke();
}```
seems a bit pointless in that example
when you guys program large projects how do you make ur code clean. do you follow a set of rules?
omg are you making a multiplayer game as well
im a beginner to netcode but im trying to make a mutliplayer game
interfaces make similar scripts that has similar features to maintain strong consistency
extension methods breaks a core scripts into smaller pieces
prefabs and SO make good templates and objects/data ready to use
thank you so much
we can assume
InputManager.Instance.joystickCore.OnDrag()```
cannot reference
```cs
MoveInput()```
or it will take me lots of efforts and loc to reference each other
data only available and generated on OnDrag()
if the event subscription is external to the class declaring it then it makes sense
i think im confused by the concepts at first place
i want MoveInput execute itself once whenever OnDrag() is called everytime, so it should be 1 on 1
moveinput should not invoke by any code other than OnDrag() execution
I have a class button with the event "OnClick". other things can then subscribe to the event to do stuff when the button is clicked. This is great because Button does not need to know about the other code
You have done it backwards 😆
if i invoking it on update when its binded with onDrag() , when onDrag is active
its 1+1 : 1+1 , then it will be 2 on 2?
i think so lol
you are invoking the event MoveInput which will CALL () => InputManager.Instance.joystickCore.OnDrag(null);
😭
joystickCore should instead have an event such as "OnDragged" that you invoke when OnDrag() is called so then OTHER things can react to OnDrag() calls.
public event Action OnDragged;
public void OnDrag()
{
//drag stuff
OnDragged?.Invoke();
}
something else can know when OnDrag() is called and do stuff
IT WORKED😭😭😭
ty 👍
hopefully that makes more sense to you now
yeah
how to make buttons clickable even with Time.timeScale = 0?
i need for them to work even if time is paused
i want to add pausing to my game
Yea but I dont think their functionality changes with time scale, animations may be afffected if using scaled time
ok nvm its my buttons
Hey, Im new to unity so watching some basic tutorials, i have a problem tough, When i create a new c# script my script generates with less code then it does in the tutorial. How do i fix this? I know i could type the missing stuff out manualy but it would save time and be a lot less annoying if i dont have to
Im not getting functions like start and update and it dosnt generate with monobehavior
public class Test
{
}
Create a MonoBehaviour, not an empty C# script. They're two different menu options.
you're creating a plain C# script
Ah, okay thank you guys!
Has anybody here looked at galactic kittens sample for unity netcode?
If so, how did you use it as a learning resource?
there is soo much abstraction that its a pain in the ass. not reccomend, imo the bitesized sample are a bit better
like 2D space shooter?
thats one of them sure, if you combine all of them you get a pretty good understanding how to approach each problem you want to solve
how should i use them tho? just read through the code
well yeah and how specific things are handled
how did you learn unity netcode
there is no like step by step or anything, unity did not handle netcode like that . Maybe the intro on docs, but to a point thats understandable you need a minimum amount of exp before doing multi
the docs kinda walks you through each samplea nd what its purpose is
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-introduction/
The Bitesize Samples repository provides a series of sample code as modules to use in your games and better understand Netcode for GameObjects (Netcode).
ok thank you
is there any way to get a Vector3 position of a random point in an area?
default answer to everything : Yes
true lol
there are several ways to do this. Also you have to consider what kind of area
What shape area?
if circular there is Random.insideSphere
or if you want something boxy Random.Range or colliders etc.
any - in my case it would probably just be a flat plane (its meant to be a waiting area that a navmeshagent goes to, rather than a single point)
It's different depending on the shape you want so you'll have to pick one
plane it is
for a flat plane you'd just use Random.Range twice
once for x and once for y or z
to pick a coordinate
that's all
If the plane is not axis-aligned, you'd pick a random point in local space like that and then essentially rotate it with either Matrix4x4 or a rotate Transform using TransformPoint
wait so what should I reference for the area, the transform?
not sure what you mean specifically
you could also do it with Lerp if you define the plane by two corner points - it depends how you want to define the plane
so ive got the transform reference, and then when i want to get a random point within that transform, what do i call?
well the Transform doesn't have points "within" it
you'd have to provide extra information like the extents of the area you want a random point within
Where is the Transform's pivot in relation to the random area?
bounds or colliders work also
i am so completely lost
im asking whether its a collider, transform or what should be the type for the area? im guessing collider if transform doesnt have points
eg new Vector3( Random.Range(xMin, xMax), etc..
eg new Vector3( Random.Range(-collider.bounds.size.x, collider.bounds.size.x), etc..
not working code just example
that seems to do it!
"type for the area" is just a really vague description. I'd imagine something like this basically:
public Vector3 SelectRandomPointOnPlane(Transform pivot, float width, float length) {
Vector3 randomLocalPoint = new(Random.Range(0, width) - width /2f, 0, Random.Range(0, length) - length 2f);
return center.TransformPoint(randomLocalPoint);
}```
it just really depends how you want to define this area
yeah thats my bad - trying to describe something i dont understand is tricky haha
there are many, many ways to do it
drawing a picture can sometimes help
oh true - ill try to remember that for next time
i am working on a multiplayer project and my only goal is publishing on steam, so what multiplayer framework i need to use. i am trying facepunch but its not feels right i am stuck on a steam relay socket creation for days. the game lobbies are probably gonna be around 40-60 person. should i use steamworks.net or go with facepunch? i wanna use steam relay sockets for privacy and security and make my game fully steam integrated.
thx
what are you supposed to do if a client leaves half way through the game in unity netcode
thats pretty vague, but also #1390346492019212368
i think we can talk about it more somewhere else
u need a more specialized channels , not here
Im trying to make a snake like game in 3d.
For the trail can I use the trail renderer component in any way to create a collidable object? or should I instantiate objects from the player character?
or any other advice for an easier way to do this would be appreciated
whats the best way to make a dialouge system in unity?
i heard some people used ink files for dialouge and some said json (even tho i cant find a single video of somenoe use json to make dialouge in unity)
line renderer would be the better choice
not everything is a video on yt.
a pre made system like inky may be best
but you said 3d , how are you going to handle that
Ink . Imo
Am I dumb? Is this not valid?
what does the error(s) say
what does it actually say, not a vague paraphrase of the error
ty!
"," was expected
thanks!
You can't use a lambda expression for a field variable
and is this at the class level? because you've declared a read-only property which naturally cannot be a local variable
Just went to open Unity today to continue my "roll a ball" tutorial and I'm met with this message:
What?
Anyone know what this is?
I just want to have a shortcut call to that reference
You can only use the => notation for functions or properties
are you trying to declare a property for the class or are you trying to declare a local variable
How do I do that?
not fields
If reinstalling doesn't fix it you probably don't meet the system requirements
RTX 3070, 32gb ram, AMD Ryzen 7 5800H with Radeon Graphics
It won't reinstall also
Then your OS is probably borked
I am trying to make a local variable for that field?
I think??
I have Windows 11 Home that came with the computer brand new
well the Type Identifier => value; syntax is how you delcare a read-only property. perhaps you should double check the characters you used and make sure they are correct 😉
can you show your singleton?
why? their issue is a syntax issue because they added an extra character
I'm... not seeing it actually
what they wrote is supposed to be a local variable but they've used the syntax for declaring a read only property. removing a single character turns that into a valid declaration for a local variable
||>||
It just stops here
and says this
Wait is it a local variable or is it a property
#💻┃unity-talk btw this is a code channel
Yeah probably OS related. If it can't install the program at all that sounds like a windows thing
it's supposed to be a local variable which is why they are seeing the error. if it were declared at the class level then there wouldn't be an error because it's valid syntax for writing a read only property
(it's valid expression body syntax for a read only property)
Is there a way to scatter prefabs onto a terrain (like the literral prefab, not just the mesh attached, like the scripts and everything)
So unity doesn't work properly on windows or are you saying my windows has something wrong with it
Yeah spawn it a bunch
I'm saying your OS is borked somehow if you can't even run the installer
With three ?
three what
The paint tree tool ?
Do you have any idea how to fix this I know it's OS related not Unity technically but everything else works fine on here literally only unity that's had an issue
Do you want trees or full objects
full object
reinstall windows
ok
Then call instantiate on it a bunch where you want it to be
The point of terrain tree instances is that they aren't full GameObjects
there is no already premade script for that ? ;-;
then what's the difference between placing tree with the grass tool and the tree tool ?
Different parameters
I want to make fpsarms and fullbodymesh depending on who isowner, where would I put the arms? The GreezyPlayer has the animation script
whats with all the network questions..
Does this not apply in this channel?
Lol he's right, whats with all the network questions?
there is a #1390346492019212368 channel
Listen here buddy, I didn't know u were the arbiter of network questions
thats certainly a way to not get your question answered...
I tried just deleting the unity hub folder completely and then running the installer and it installed fine and works now
I need help finding out how to look at objects from the left in the scene I have a video
Position the camera on the left
Doesn't really have much to it, it should be matching, I am not sure what I am doing wrong
Like this is basically what I am doing right? I don't get it....
how do you declare a local variable
like just as an example, declare a local variable of type int and assign it a value in the same line
private float variable = 1f; is this what your asking
yeah well, then send the video 😄
there you go. you even fixed your issue
notice how in both cases now you are using the assignment operator = and not the expression body operator =>
i was not asking for help there lmao
are you asking how to rotate around the object?
But like I don't want the new variable to be equal to the thing, I want it to point to the thing so I can modify the thing from there
wdym by "modify the thing"?
because even if it were a property you still wouldn't be able to change the object referenced in that variable you used in the assignement
so when I press the top right thing it at 11 seconds, it looks at the left but flips it, I want to be looking at the left of the object and orbit around it as if I'm looking at all the sides. An example is walking around a chair and facing it
you would still only be able to modify its public properties/fields
It always goes to an upright view
press F to focus the object, then you can press alt + left mouse button to rotate around it
What do you mean by "normally", that seems pretty normal?
when I mean normally I mean walking around a chair and looking at it
when I look at the left wall of the cube it rotates it or flips or something
ive seen a video where the person is looking at a object and is flying around it while facing it
thats because you are standing sideways in the room looking at the chair 😄
you start looking at the cube from the top, ofcourse it flips when you then switch to the side
yeah, how do I make it not do that and look at the cube like the video
can you send your first video again?
It still seems like you're just doing normal camera movement so I'm not sure what the issue is
your up arrow is not pointing up
what do you mean
the way the arrows point is backwards, not up
according to the youtube video, am I doing what the guy is doing 7 seconds in
I literally do not see anything wrong with this
he is wondering why the rotation is behaving weird, its because his cube is rotated wrong
is this local or world ?
nothings wrong with the movement I just want to know how to look at it without making it flip the camera and stuff
I dont know what that means but I havent messed with settings so its the default
local
that syntax u wrote is nonsense
this is how it behaves if you have the orientation right
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 191
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-07-31
this is how it behaves if you have the orientation wrong
Yours isn't the same
They've underline where you've made a mistake
you basically start looking at the cube from the top, then flipping over to the left, which causes the view to flip
how do I fix the orientation
your cube is flipped on its side right now
make sure on the cross top right the green Y arrow is pointing up
and then rotate the cube so the upside of the cube points the same way
this will fix the scene camera
yes
Thanks
Yo who knows how to make a grabbing system, like making a system where you can grab a box or smth
Lots of people know how to make one.
Do you have a specific question?
Usually using raycasts
Can someone post a code here so I can understand
Like any problem you'll need to break it down into parts:
- Detection of an object in range in front of the player
- The "grabbing and holding" part
just posting arbitrary code won't help you much. Basically:
- For the detection of the obejct you would use a raycast
- For handling the input, you would use normal input functions like Input.GetButtonDown
- For holding/grabbing, you would either teleport the object to a specified position in front of the player each frame, or use physics e.g. setting velocity to move the obejct towards that point each FixedUpdate
"Grabbing system" is not the most granular way to express this idea. Make it smaller and more specific. Amnesia, Half-Life, Super Mario World, and Donkey Kong Bananza all have "Grabbing systems"
What if you use Vector3.distance to check how far it is from player and then mouse down so you can grab it instead of using raycast
Does it work

It would work if you want to grab objects anywhere in a spherical area around the player and if you want it to be really inefficient (because you'd have to do that distance check for every grabbable object in the scene), sure
if you want to only be able to grab objects you're looking directly at, you would use a Raycast
Oh dear, what's happened here. This exact same code worked fine in a previous project.
Ah, I see
I don't believe it did. GetButtonDown has always expected an InputManager button name
You're confusing GetButtonDown and GetKeyDown
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
any idea why this results in all the passengers being taken in instantly when PassengerSpeed is 3? https://paste.mod.gg/pfjksxobciqi/0
A tool for sharing your source code with the world!
and I mean like over 10 instantly
kinda random but what are yall working on rn?
Debug it
Maybe not the right channel for this question. Also, you can see in #🏆┃daily-win
is there any case where its better for the logic script to have direct access to the UI or should I always just have the UI reference the logic script and subscribe to its events?
minor detail i know
Rather than setting the transform position for all 4 bounds to keep something in bounds, is there a way to keep something within the bounds of a plane?
Cause all I'm looking to do is keep the ball within this square plane, so I'm wondering if there's an easier way to do that
you could use OnTriggerExit maybe?
The latter is usually better.
and make a big collider
Hmm, I was wondering if there was data in the plane I could use
what do you mean data in the plane?
In my brain I'm just thinking there has to be data that tells unity where the planes X and Z axis stop, but maybe I'm just making that up and all it knows is it's position and scale
You could probably check against the plane bounds(x, z) in code and prevent the ball from going outside them.
If it's just an empty object, then yeah. But renderers and colliders have bounds.
if you want physics wouldn't invisible colliders just be easier though?
Could someone help me about the game scale?
once i put it on full screem it got like this
Yeah, it's got a mesh collider. How do I find info on the bounds for it?
but when i keep it on the editor it stays normal
Hmm, this might be too ambitious for my current skill level
what exactly are you trying to do? make it bounce around the edges?
or if it touches the edges it stops completely, are you using physics?
Nah, make it so it can't go past the edges
I'm using transform.translate for x and y, but I'm using addforce for jumping
If that matters at all
so you want effectively "invisible" walls?
Yes
simplest way is just make invisible boxcolliders around the edges
but it can be easily done using the bounds of the meshcollider of the plane
I'd need to see how it's written to understand
in an update loop you would check the position of the ball and compare it to the world bounds of plane, if they are over then set the position of the ball to the edge
but you would have to account for the radius if you dont want clipping, etc
Probably too complicated for me right now. Someone should help Okane instead 😂
i would just make boxes around the edges 😂
Probably easier, but I like the idea of precision
no reason they aren't precise?
something is wrong with your CanvasScaler component
I could also make it precise with transform.position, but I liked the idea of something that would adapt if I made the plane bigger, and also wouldn't require me to make 4 if statements and 4 variables
yeah it wasnt sacaling with screem size
colliders would need 0 code haha and using EdgeColliders would be super easy
wait maybe edge colliders are 2d only
Yeah, I suppose, but I'd also like to be able to code the solution. Putting an invisible block in the way feels like the easy way out 😂
Like how they couldn't get trams in fallout working so they just make the tram a helmet and attatched it to an NPCs head 😂
you could make a meshcollider and invert the normals so it acts like walls, that would require code
it could also be super easily resized to the plane size in code
I'll probably leave it then since I don't understand some of those words yet
haha, you could always ask AI to give an example to understand the code
Colliders need not have mesh renderers.
Spawn an object, put a box collider on it, scale it to the size you want and you're good
GPT gave me something, but I'm probably getting lost in the weeds here
i just dont see why you need to do something that unity physics already does and probably does better
if its the resizing, you could make a simple script that resizes the boxes exactly to the borders of the plane
How can I explain this....
Imagine someone only knows how to do addition
You ask them to get the result of 6 lots of 10
They'd just say "10 + 10 + 10 + 10 + 10 + 10 = 60"
And then you're like "you know multiplication is a much better way to do that?"
And the asnwer is no, they don't, because they don't know multiplication yet
i understand but in this case that multiplication is not only much better but its much easier than addition
if you insist on using code you would do what I said above
just use physics or if you want to control the transform directly just get the bounding box of the plane and use that compute your movement limits
And yet, this is what I actually understand how to do at my current level.
if (transform.position.x > xBounds)
{
transform.position = new Vector3(xBounds, transform.position.y, transform.position.z);
}
else if (transform.position.x < -xBounds)
{
transform.position = new Vector3(-xBounds, transform.position.y, transform.position.z);
}
else if (transform.position.z > zBounds)
{
transform.position = new Vector3(transform.position.x, transform.position.y, zBounds);
}
else if (transform.position.z < -zBounds)
{
transform.position = new Vector3(transform.position.x, transform.position.y, -zBounds);
}```
all colliders and mesh renders have a property to get these bounds
getting xbounds then -xbounds makes no sense and would be just wrong or twice what you want
also instead of using if's using Mathf.Clamp will be much easier to read
you can construct a new vector where the x and z axis are clamped using the max and min x z and z of the bounds
is there something complicated about putting walls around then making them invisible that i dont see, not trying to be rude
I need some help
Not really, but like I said, it's coding that I don't understand, I already know how to put a big invisible box in the way to stop something, that's easy, but I don't really learn anything from doing it
ah i see
Blame unity tutorials for teaching me to do things that way
not everyones game uses physics directly even in a heavily movement based game i am doing for work all movement is our own logic
I was coding a timer into a combo attack I have in my game, I want it to give you a certain amount of time to hit the enemy 4 times or it resets the value, snd I got it working where when I press the attack button the ComboTimer counts down, but currently it doesnt work like a clock, if decreased a little bit each time I press the key, but I want it to fully activate the timer with just the first click…
transform.position = new Vector3(Mathf.Clamp(pos.x, xMin, xMax), pos.y, Mathf.Clamp(pos.z, zMin, zMax));
way simpler
Possibly, but I haven't learnt about clamp, so you know
the min and max values you would jsut get from the bounds of the renderer
like everything else in Mathf its a pretty simple basic math function
clamp is more of a math concept not coding
its like if you combined a min and a max or if you just did conditinals for the lower and upper range
<@&502884371011731486>
!softban 1400114281630142598 bot spam
joanna_dwayne0928 was softbanned.
when the button is activated you set a bool, while that bool is true, you add or remove Time.deltaTIme from a field and check if it has reached 0 or gotten to your duration
i mention add or subtract since some people like starting timers and 0 and counting up to a duration others like setting the timer to duration and working down to 0
I feel like im heading into manager hell. I previously have used ScriptableObjects for inventories since it allows me to plug the inventory into anything that needs it, for example the players inventory into the shop without it needing a reference to the whole player. However, SOs are awkward to save and serialize and are also a headache to create an runtime (for example a randomly spawned chest's inventory). Im instead going to make inventories just a POCO so they can easily be created at runtime, but now I have the issue of things needed references to them. would a InventoryManager singleton be a bad idea for this? It feels like everything needs a manager haha
coupling happens at some point its your choice where that happens
but yeah i would just handle things like that that do not require unity features with just regular objects as well
so go down the route of an inventory manager? i guess another solution would be dependency injection but i dont really like that in unity tbh
find with unity really most projects end up with some sort of manager singleton type stuff going on
since in unity you do not control the entry point like you would in a traditional application so its harder to pass dependencies down the stack
personally i would try and still get control over when its created and not just let the singleton pattern create it. Perhaps have 1 object that contains constructs and holds reference to a bunch of stuff like this
but yeah i am not really a fan of dependency injection frameworks either, rather just pass things around myself or provide a other way
could you elaborate on this? like currently for a lot of my systems, i have the object itself hold a prefab (if its a gameobject) or something similar, and have the singleton create something with it. is there a better way to do this?
for example, with my UI, the object holds a prefab of the window and the UI manager spawns the window on a canvas that all other UI goes on
i thought you were purely talking about the data representation of inventory