#💻┃code-beginner
1 messages · Page 833 of 1
with isGrounded, if you're on the ground and jump is pressed, the upwards velocity gets set.
without isGrounded, if jump is pressed, the upwards velocity gets set.
I understand why removing isGrounded allows me to air jump but not why it makes jumps higher
if you don't have the isGrounded check, you get to jump even while already in the air, and it seems like that JumpPressed checks the current state of the button, instead of whether it was just pressed down
try holding down jump
same result
i seperated pressing down and holding in inputhandler
they're basically different inputs
could you show that
need to get around discord message size limit rq
the embed you were linked has a section called "Large code blocks"
consider reading that
private void OnEnable()
{
actions.Enable();
actions.Player.Move.performed += ctx => MoveInput = ctx.ReadValue<Vector2>();
actions.Player.Move.canceled += ctx => MoveInput = Vector2.zero;
actions.Player.Look.performed += ctx => LookInput = ctx.ReadValue<Vector2>();
actions.Player.Look.canceled += ctx => LookInput = Vector2.zero;
actions.Player.Jump.started += ctx => jumpDownRaw = true;
actions.Player.Jump.performed += ctx => jumpHeldRaw = true;
actions.Player.Jump.canceled += ctx => jumpUpRaw = true;
actions.Player.Crouch.performed += ctx => crouchHeldRaw = true;
actions.Player.Crouch.canceled += ctx => crouchHeldRaw = false;
actions.Player.Sprint.performed += ctx => sprintHeldRaw = true;
actions.Player.Sprint.canceled += ctx => sprintHeldRaw = false;
}
private void OnDisable()
{
actions.Disable();
}
private void Update()
{
// ---- JUMP SNAPSHOT ----
JumpPressed = jumpDownRaw;
JumpHeld = jumpHeldRaw;
JumpReleased = jumpUpRaw;
// clear edge triggers after snapshot
jumpDownRaw = false;
jumpUpRaw = false;
// ---- CROUCH ----
if (CrouchToggle)
{
if (crouchHeldRaw)
{
crouchToggledOn = !crouchToggledOn;
crouchHeldRaw = false; // prevent rapid toggle spam
}
CrouchState = crouchToggledOn;
}
else
{
CrouchState = crouchHeldRaw;
}
// ---- SPRINT ----
if (SprintToggle)
{
if (sprintHeldRaw)
{
sprintToggledOn = !sprintToggledOn;
sprintHeldRaw = false;
}
SprintState = sprintToggledOn;
}
else
{
SprintState = sprintHeldRaw;
}
}
i dont think the rest is relevant anyawy
oh mb
there's definitely something missing here.
that seems normal. have you tried debugging to see if it's getting into that if multiple times?
the if inside jumphandler?
yes
Only once per spacebar down and not when I press space midair
so yes it's getting into it only once
what if you don't have the grounded check
the jump has a proper height and feels more natural
u are right, it triggers twice without isGrounded
(btw your OnEnable and OnDisable seem like you expect this to be disabled/re-enabled, but that'll end up with stale event listeners since you never unsubscribe)
thx for pointing that out
When the player dies, I do
var name = SceneManager.GetActiveScene().name;
SceneManager.LoadScene(name);
But I want to preserve the death count. How do I preserve state across scene loads?
you need something that persists across scene loads, that doesn't live in the scene
that could be a gamemanager that's DDOL or in a persistent scene for example, or a save file
What is DDOL?
dontdestroyonload
Any tutorial how do you make it?
try googling like, ddol/singleton gamemanager, i guess
@delicate ferry Just do this whenever you want to create a single global access point to your application/game, specifically you do it for managers because they are responsible in controlling things like UI, Game States etc
public static GameManager Instance;
and then you do something like
{
Instance = this; DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}```
This is called Singletton Pattern. Keep in mind that each pattern has pros and cons. You dont have to make every class a singleton. This code btw will let your game objects persist across scenes, also something I didn't know before is that even if you change more than one scenes your objects will still be persistent because it actually stores your game object on a seperate scene called DontDestroyOnLoad and that's really cool.
Where do I put the code of gamemanager?
the instance declaration goes after your game manager class and you declare it as static. The if statements go in awake because we want the instance to be created at the moment your script is loaded/created when you play the game. If that's what you mean?
Thanks
https://unity.huh.how/references/singletons just remembered this exists
Okay thanks
But now in what scene do I put the gamemanager? Eventually my game will have multiple scenes
First scene I would say
with this approach you'd have it in every scene for ease of testing
or if you only have it in one scene it'd be simpler but you wouldn't be able to play from other scenes directly
you could also use a persistent additive scene to avoid that issue but it's a bit more complex
So if I have a gamemanager object in every scene with the same script, the state is preserved right?
the state is preserved because the original object persists, not because it's in every scene
it being in every scene just means you can enter playmode from anywhere
It's not efficient though at all. Just keep in mind that. That's very risky making more than one of the same managers in your game. I think we had a discussion about it with another guy. You always have to think about the Single Responsibility Principle and if you have duplicates you are breaking this principle that means harder to maintain and manage etc etc because imagine you have some references on one scene and some references on other scene for the same game manager you will probably have many null references because some objects dont exist on the other scene you have the duplicated game manager thats horrible approach.
it literally doesn't matter
it's not related to efficiency at all
if you have references to objects in the scene, that is an issue of design - the gamemanager shouldn't care about stuff in specific scenes
YYeah
What I am saying is just do the DDOL + Singleton dont create duplicates in all of your scenes.
so you're locked into opening 1 specific scene and going from there to test anything in playmode, sure...
having duplicates doesn't matter anyway if you have the Destroy(gameObject) set up correctly
RuntimeInitializeOnLoad can solve both at once!
What is this?
i guess for non-component singletons, i don't this would work for component singletons, would it?
since you'd need a component instance
if you don't need the editor to populate fields, then there's no problem
fair
actually, i feel like having an inspector would still be very useful for debugging purposes
if it's not a component you can't directly inspect it from the editor at all
i haven't considered this approach before so having a lot of thoughts lol
Absolutely, and if I had to lean on one side, I definitely prefer having duplicates across scenes to avoid forcing a scene on load
Sorry, I meant absolutely to the first statement you made
That being said, you can init a GO and strap your component to it and then do your typical singleton logic from a method with the attribute above.
Then the only thing you're really losing is the ability to preset variables via the inspector
That being said, you can init a GO and strap your component to it and then do your typical singleton logic from a method with the attribute above.
i feel like this mix of approaches causes kinda more problems, does it not? (kinda minor problems, but relatively, more)
you'd have to retreive the component reference from that static method
or i guess you could have the component depend on the singleton logic rather than the other way around? 
eg either the method creates the singleton component, or the component is just for introspecting the singleton
If you don't need persistent values defined via the inspector, then there's nothing stopping you from
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Initialize()
{
foo = new go
staticInstance = foo.AddComponent<InstanceOfYourSingleton>
DDOL(foo)
}
this way you can forget about it whenever you create new scenes, but you can't use the editor to populate fields. I guess you could still load the instance as a prefab if you really needed this
you wouldn't be able to grab the prefab reference
well, not easily
would need magic strings
I don't follow. Why so?
well, how would you get the prefab reference from the static method lol
would need to go through eg Resources.Load instead of having a direct reference
You can expose a static API that retrieves your content via whatever your preferred method is. I am not familiar with addressables so I can't speak for that but resources.load would work just fine
you'd need magic strings either way though, no?
wouldn't be able to assign a direct reference, is what i was trying to say
Yeah, that's true I guess. I still advocate for it though. If they bother you so much, you can have a single magic string that acts as a point of entry to your data. Map it as a constant and forget about it. I understand where you're coming from though
i have a habit of wanting to rename/restructure/refactor a lot so i try to avoid magic strings like the plague lol 😅
yeah, I hear you. You know what's good for you based on your flow, there's no arguing against that. For me, integrating singletons like this were a net positive, but I don't expect that to translate to all workflows
do you have a coding question 
no, just surprised.
this channel is for coding help
I guess #💻┃unity-talk would have been more appropriate
sorry, I'm so used to only using this channel lol
i wouldnt even say that, because its also not really a question lol
unity-talk is for general unity questions
not a genchat
I see. I will keep my mouth shut then
(fyi, this topic would be for #🖼️┃2d-tools or maybe #🔀┃art-asset-workflow - but yeah typically discussion/questions are expected rather than chatter)
I cannot find how I would check if the scroll wheel is being scrolled down or up using the new input system
are you not finding the binding or control or something else?
actually i should ask, how are you receiving input?
so i can point you to the corresponding way to get mouse scroll
Thing is, I'm looking for something similar to the ispressed functions but for scrolling instead
on an InputValue or on an InputAction?
uhhh.... action, I think
just check the stuff you're reading isPressed/IsPressed on, see what type it is
or show the code if you can't find it
could also be InputControl, or maybe CallbackContext. i don't know the full list
it stands for a new Vector3(0, 0, 0)
The vector only has 0 in it, so it does not move anywhere.
okkk!!! Thanks!!
Also works with Vector2
it's a prop that's just Vector3 zero => new Vector3(0, 0, 0);
it's the same as creating that yourself, just a handy shortcut that communicates a little more intent as well
So should I go for Vector3 zero => new Vector3(0, 0, 0) or with the one with .zero?
what i wrote is how .zero is defined
oooh, ok
it's not exactly that, but the same behavior
you can see the actual definition here
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs#L424-L425
or in your own ide by using "go to definition" (ctrl+click the zero)
tyy
So what's the difference with Vector3 and Vector2?
one is 2d and the other is 3d
hey im unsure if this is possible but, i have 3 buttons, and i want to set a single variable based on which button is clicked. is that possible to do while only making 1 function for it? or do i need to make a separate function for each button?
a single function with a parameter works
Is there a good guide to understand how ActionMaps, Input Handler and a tick based physics loop process inputs? (for FPS games)
there are input and inputsystem guides online and on unity learn, if that's what you're asking?
Since Vector3 is made for 3d, it uses three values (x, y and z). Vector2 however only has two (x and y) for 2d.
ugui?
i don't think there's gonna be anything specifically for that, because.. that's not really a different usecase
im sorry whats ugui/uitk?
ooooh, thanks man!
sooo did you find what inputsystem structure you were using
no 😭 im making a unity discussions post rn
Unity ui (canvas)
why didn't you just ask me for clarifiaction lmao
im waiting for you to answer
there's multiple ways to get input in the inputsystem
i'm asking what you're using so i can tell you how to get scroll input in the same way
Does += mean take the current value and add 1?
just go to where you're using ispressed, and hover over the thing in front of the . (or show the code)
you might just want to go do some beginner c# tutorials instead of asking everything here
it will be much faster for you and for us
there are resources pinned in this channel
okkkkk
did they change onClick in code to EventSystem.currentSelectedGameObject?
No you are very very confused
srry im trying to figure out how to invoke onClick in code
Ugui Button still has onClick
You don't
Unless you call OnPointerClick on the button itself
rn im doing this (i solved my problem btw)
public void ToHumanCount()
{
GameObject clickedButton = EventSystem.current.currentSelectedGameObject;
if (clickedButton.name == "2 players")
{
PlayerAmount = 2;
}
else if (clickedButton.name == "3 players")
{
PlayerAmount = 3;
}
else if (clickedButton.name == "4 players")
{
PlayerAmount = 4;
}
but i wanted to do it a different way originally
OnPointerClick...
why not just receive an int here and have the buttons pass on that int
This is horrible wut
you can set that int in the event you set in the button
and yeah that is incredibly fragile
Exactly
i was trying that originally but it wasnt actually changing
Share that attempt
yeah im aware thats why im trying to figure this out
you can do exactly this
Id write an example but I'm on mobile rn
public int PlayerAmount;
public enum PlayerCount
{
players2 = 2,
players3 = 3,
players4 = 4
}
public void SetPlayers(int players)
{
PlayerAmount = (int)players;
switch (players)
{
case 2:
PlayerAmount = (int)players;
break;
case 3:
PlayerAmount = (int)players;
break;
case 4:
PlayerAmount = (int)players;
break;
}
}
public void ToHumanCount()
{
ShowState(MenuState.HumanCount);
SetPlayers(PlayerCount);
}
The problem is that idk what to really call in SetPlayers() and maybe something else i havent thought of
holup
Easiest solution for you is a new script that stores this data on each button and you read this when each is clicked.
what even
you're overcomplicating this
you have the same logic in every branch of that switch
also this isn't even valid code?
i'm so confused what's going on here
i said holup for areason lol
yeah that's fair
Oooh, it's basically just +1
ToHumanCount is the method you're using for the button's onclick, right?
it is not
It says +(Vector3 a, Vector3 b)
yes
that's an operator overload signature, that doesn't say anything
the code should just be this then```cs
public void ToHumanCount(int amount)
{
PlayerAmount = amount;
}
If I have an object flying at Velocity, iis this the vay to make it face the way it goes?
transform.rotation = new Quaternion(0, 0, Vector2.Angle(Vector2.up, Velocity), 0);
If I have: Vector3 g_moveDirection = Vector3.zero; that means: (0, 0, 0)
then I'll do: g_moveDirection += Vector3.forward; and it gets to: (0, 0, 1)
now I'll do: g_moveDirection += Vector3.right; and that gets to: (1, 0, 1)
definitely not. you should not be modifying quaternions yourself
It doesn't seem to be
So how?
Velocity is the velocity vector?
Yep
yep, and it's addition, not +1
oooh, yeah, I meant that
and you want the object's forwards direction to point in that direction, right?
Yeah
you can do transform.forward = Velocity; then
it might be forwards, i don't remember
if you have angles, you could use something like Quaternion.Euler here, but it's an unnecessary step for this case.
the problem is still that i have 3 buttons, how would it know which one represents what number?
you can set the parameter in the onclick binding
huh?
this is what john was referring to
They don't understand lambdas
I suggested a script to put on the buttons but who knows
It makes the object fly away
I'm tired 😩
go to your button and set the onclick to tohumancount (you might need to remove and re-add it)
there will be a input box that shows up. that will be the int amount
no i do not
Wrong channel, isn't it?
this just sets the rotation, it wouldn't affect anything like that
<@&502884371011731486> job post/spam
Make new script to store number, put on each button, get component in the on click listener and get value bam dynamic and shit
Weird
can you not just.. use the onclick
ohh i see
I'm just telling them a method suited to their current skill
I'm very aware of better designs but it beats using names
Apparently I am getting Look rotation viewing vector is zero
no clue what that is
But the vector is not zero
i'm not in your project with you
yeah but wouldn't this be easier
i figure u dont want to type everything out for this... can u tell me what to look up?
yes this worked i appreciate you
it's just this
it's less work
Unity is saying that
It's not anything in my project
ah, i see
Ah you meant specifically inspector subscription to enter the arg mb
i guess make sure Velocity is valid before assigning that
I presumed code sub
It is valid
are you sure it's that frame thouhg
Yeah
try logging Velocity before you assign it to transform.forwards
thx guys 
how would you know, did you go frame by frame lol
Apparently the issue is that it transforms x and y
It's a 2d game
I want it to only transform z
Apparently I needed transform up instead
ah yeah, in 2d you don't typically want to change the forwards direction
Left = -Right
True
Big brain
Does anyone know if fog of war and a chunking system (For memory management) should be implemented at the same time? Because i think chunking drastically changes how AI move and things happen inside the fog of war of a chunking system where things arent being constantly updated but they still exist and do things persay
Yea if you have a shared system for splitting up your world/scene into a 3d/2d grid
It is. Nice i have no idea how to do this and i fear object geometry, environment, seed rng biomes, rng resource spawning etc is all intimately connected with the fog of war/chunking
Im so screwed
Im guessing this is the hardest part of everything maybe aside from balancing which is the real nightmare
Im likely going to hire someone for the balancing part. It will probably be expensive as well unfortunately to pay someone to do it. But if anyone is interested in a future job u can mark me in ur dms or whatever if its something any of u would be interested in working on
If I contact you please have a resume on balancing ready
Trying to reference a variable from another script in another game object like this:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Count : MonoBehaviour
{
[SerializeField] TextMeshProUGUI textObj;
[SerializeField] private Chris Ref;
void Start()
{
Ref.money;
}```
it gives me the error ```Assets\Count.cs(5,7): error CS0246: The type or namespace name 'Chris' could not be found (are you missing a using directive or an assembly reference?)```
what did I do wrong here?
what is Chris
a Gameobject
no
that contains a script with the money variable
what is that script called
Click
i thought i was supposed to reference the gameobject, not the script
no, but even if you did you would do private GameObject Ref
alright, works now, thanks
that was a pretty obvious solution, and i tried things before asking, I swear!
alright now it says money doesn't exist in the current context
post your Click script code
using UnityEngine;
public class Click : MonoBehaviour
{
float sizeincrease = 0.1f;
int iterationCount = 3;
float delayBetweenSteps = 0.02f;
public int money;
void OnMouseOver()
{
if (Input.GetMouseButtonDown(0))
{
money += 1;
StartCoroutine(ScaleOverTime());
Debug.Log(money + " christonium");
}
}
IEnumerator ScaleOverTime()
{
for(int i = 0; i < iterationCount; i++)
{
transform.localScale += new Vector3(sizeincrease,sizeincrease,0);
sizeincrease += 0.1f;
yield return new WaitForSeconds(delayBetweenSteps);
}
StopCoroutine(ScaleOverTime());
transform.localScale = new Vector3(2,2,0);
sizeincrease = 0.1f;
}
}
also, the serialized field in vscode and the unity editor dont match
"Chris" is mentioned nowhere in the Count script and yet its the label for the serialized field
do you have errors and have you saved your script
yes I've saved it, and these are my errors:
Assets\Count.cs(17,24): error CS0103: The name 'money' does not exist in the current context
the serialized field thing was weird to me so i deleted the script and copy pasted its contents into an identical one, now there are no serialized fields
you need to fix all compile errors before your code can compile
makes sense, I still dont know how to fix the error, it seems like i did it right?
in the code you pasted above it does look correct. but have you saved that too? (assuming that's even where the error is)
yeah, everything is saved
and are you looking at the Count.cs file?
actually, the Count script changed a bit from when i pasted it,
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Count : MonoBehaviour
{
[SerializeField] TextMeshProUGUI textObj;
[SerializeField] Click Ref;
void Start()
{
}
// Update is called once per frame
void Update()
{
textObj.text = money;
}
}```
so this is where that error is. not in the Click class you pasted above. where have you declared money here
money is declared in Click
What is money
no, i'm talking about the money variable you are trying to use as part of the Count class. that's totally separate
This isn't Click, this is Count
and (at least what i tried to do) was reference money from the Click script
an integer from click
Then you would want to actually use your reference
You're getting the text variable from your textObj
Do that
holy crap, that's so obvious
Obvious enough to show that you should definitely go through the very basics again. There are some courses linked in the pins, go through them.
this is kinda my way of going through the basics, ive never gotten anywhere from courses, as I get bored and retain nothing
stumbling along until someone else tells you how to fix things isn't exactly a good way to learn anything
thats why i've been looking at documentation and old forum posts up until I hit this wall
but yes, thats correct
So, instead of reading forum posts, you could read a document that is specifically designed to teach you this thing
sure,
what I meant by not following courses was not going through lessons one by one doing the exact same thing it tells me to, instead of making my own thing along the way
so modern games
with no loading screen after mission finish and all
technically has whole game in one scene?
and loads next batch of assets during narrow passages or other hacky ways?
can't have an entire generalization like this lol. not every game is the same
no i mean that kind of games
seamless loads are a thing, chunk loading is a thing, etc
that has no loading screen
there's so many ways to do it
additive scene loading
several games don't have loading screens
undertale doesn't have loading screens
do they have unique levels in unique scenes or same scene?
in unity terms
could have either
you can have scene a loaded, load scene b, then unload scene a
might not even have separate levels
you're asking for a generalization that doesn't exist
how can change scene without loading or something?
you can have multiple scenes loaded at the same time
you can have loading without a loading screen
i am newbie sorry, making myself clear
i don't think additive scene loading is the answer here tbh
the question is way too vague to actually have a proper answer
so to move from one scene to other, we need some sort of transition?
not neccasarily
ok so my main problem is. I am building a game and i do not want loading screen. Should i go with one scene for the whole game?
not just because of that, no
those are separate concepts
you can change scenes without a loading screen, you can have loading without changing scenes
by loading screen, i mean: finishing a level and u get to main menu or some other menu and then u start from some unique place
next level
what i said doesn't change
wasn't there that one spiderman game on ps5 where a scene change was completely seamless, for example
changing scene makes sense when the next scene start from unique place and unique environment?
think of actual scenes irl
if you have, eg, the inside of a building that's disconnected from outside, then that could be a separate scene
if it's connected to the outside, then it wouldn't be a separate scene
you can have a single big scene by loading/unloading stuff within the world yourself, that is an option
it's too vague to be bad or good practice
yeah that would make things complexier i believe
is it allowed to show 1 minutes video of my game if you can have a better idea seeing it wat kind of game it is?
i wouldn't care tbh
it's like this, u keep going forward without any transition or anything
are there pros and cons of having whole game being in one scene vs multiple scene
like listed
not listed, no
again, this is way too vague
don't worry about this
just design it in a way that makes sense
it's all continuous in the same world? sure, one scene.
there are separate disconnected areas? sure, different scenes
it's not that deep
you should not be deciding whether to use one scene or multiple scenes
you should be deciding how you want your game to flow, and then the decision over how scenes go will just pop out of that
ok this helps thanks ❤️
!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.
Why does this script not work:
List <Vector3> MapPoints = new List<Vector3>();
Vector3 lastPoint;
float distanceThreshold = 5f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
if (MapPoints.Count == 0)
{
AddPoint();
}
}
// Update is called once per frame
void Update()
{
float distanceSquared = (transform.position - lastPoint).sqrMagnitude;
if (distanceSquared > distanceThreshold )
{
AddPoint();
}
}
void AddPoint()
{
Vector3 currentLocation = transform.position;
MapPoints.Add(currentLocation);
lastPoint = currentLocation;
Debug.Log(MapPoints.Count);
//Debug.Log(lastPoint);
}
The Debug for points.count always shows 0. Furthermore, it triggers every frame, whereas it should trigger only every x distance moved
You're looking at some other log output. Change it to something more descriptive: Debug.Log("MapPoints count: " + MapPoints.Count);
ah you were right
Guys any of you build some good working publishable or semi publishable quality level multiplayer game. How do you guys learn the multiplayer concepts using fusion, theres docs and stuff but some things like optimizing data thats sent over network or some industry standard methods. Are there any good resources which teach you in depth photon fusion and multiplayer in general (Not the basic two player spawned logic)
A lot of the "industry standard methods" you want are implemented by Fusion, so I would just study it until you have a good grasp of it. Use #1390346492019212368 or the Photon Discord for networking questions.
Ohhh, No like I mean some guide to start on some things, Cuz that channel has different threads of different topics
One of the threads is a general chat a lot like this one, but specifically for networking.
I am really confused, I've made a reference for the Transform component countless times, but for some reason Unity thinks the namespace doesn't exist? There's literally a reference to Transform in a different script in the same project that works fine
....wait. Ohhh my god I forgot to capitalise this instance the entire time, I didn't read what column the error was on, ahg
you need to configure your ide
!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
it'll show you were the error is
also you shouldn't name a field transform, you won't be able to access the object's own transform lol. your ide will also warn of this if configured properly.
oh wait you're doing this.GetComponent<Transform>?
why would anyone need its own custom property transform if you have it already out of the box?
why do you even have that transform field lol
you never need GetComponent<Transform>()
you can just do targetPlayer.transform @small summit
i smell some shatgbt hallucinations in this approach 😄
targetPlayer doesn't seem to be assigned either lmao
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody rb;
private Vector2 moveInput;
public float speed = 5f;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
void Update()
{
Vector3 move = new Vector3(moveInput.x, 0, moveInput.y);
rb.MovePosition(rb.position + move * speed * Time.deltaTime);
}
}``` any idea why this is not working?
what you expect to happen vs whats happening
capsule player should move, but it doesnt
put some debugs and see whats running
are you getting any errors, check if OnMove is being called
I dont know how to check that
the first thing you should've learned.. print logs..
oh thats working, I tought you can visually see what methods are called
you can with a debugger, but this is a quick and easy analog that's easier to explain for beginners
so have you figured out the problem ?
kinda, i switched from a rigidbody to character controller
ehh it should work the same tho..
I thing it was this line rb.MovePosition(rb.position + move * speed * Time.deltaTime);
I have the feeling it only moved the rb position but left the player position in place (im not sure)=
that sounds more of poor setup in the hierarchy, the code itself is fine
but I couldnt write rb.MovePosition(move * speed * Time.deltaTime); like i did with character controller. But I dont know what the additional rb.position did, VS autofilled it and it gave me an error without it
I didnt do anything with the hierarchy and it works now
there shouldn't be error without it , rb.position helps it move relative to its own current position
because they work differently
guys what is the best method to learn unity coding
not just basic funtions like advanced movement
can anyone help me how can i make the trail renderer curve smoothly? it only moves in square (sry idk how to expain it) like i cant make an s shape
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start from basics
ty
that doesn't seem like a #💻┃code-beginner question
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.MovePosition.html
oh lord....why does the doc use transform.position instead of rb.position 🙄
was the RB not on the same object as the player? it sounds like you had it as a child
having a cc as a child wouldn't be correct either
oh where can i ask then
not sure, probably #1390346776804069396? they might redirect you again if i'm wrong
for me both work without me knowing how so I switch stuff around, change stuff in the code until something works
okay thanks
so maybe get some understanding instead of doing trial and error
why dont you just use the Splines tool.
line renderer is finicky making curves
you don't actually learn much by just doing trial and error
well im still learning so i have no clue about splines tool but i'll look into it if it works better than trial renderer
I googled unity rigidbody and there was no anwser to it. I looked here https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.html and here https://docs.unity3d.com/2017.2/Documentation/Manual/class-Rigidbody.html
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
right because the issue was in the hierarchy, by the sounds of it
also isn't MovePosition just for kinematics
for a dynamic RB you'd be using velocity or AddForce instead, and those are relative
actually for 2D it might be a bit more difficult to use it directly.
depends what you're doing i suppose
oh wait thats trail renderer not line renderer, nvm scratch the thing about splines. mb
Ive read that rigidbody is more for objects and not the player so I will use character controller from now on. One thing at a time. also is that movement script good or is not good readign the input in update all the time? ```using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
private Vector2 moveValue;
[SerializeField] private float speed = 7f;
void Awake()
{
controller = GetComponent<CharacterController>();
}
public void OnMove(InputValue value)
{
moveValue = value.Get<Vector2>();
}
void Update()
{
// directional movement
Vector3 move = new Vector3(moveValue.x, 0, moveValue.y);
controller.Move(move * speed * Time.deltaTime);
}
}```
Ive read that rigidbody is more for objects and not the player
where did you get that?
you can definitely use RBs for players
oh well no worries thanks for trying to help 😄
is not good readign the input in update all the time?
not reading it constantly would mean your game is laggy
I didnt say you cant but they come with a bunch of limitations to work around. I saw it a youtube tutorial
they have some limitations, yes. everything else also has limitations
pros n cons.
like everything else
some "limitations" in one context may also be benefits in others
don't just "oh i'm not using RB because some youtuber said so", figure out how you want your player to behave and go from there
character controller is just easier in the sense that gives you the kinematic controller without having to do your own casts for collisions like kinematic RB
dont know what kinematic is and how to use it
kinematic = not affected by external forces but still affects other physics body. oversimplified.
is CC able to send forces?
you can use OnControllerColliderHit and use AddForce otherwise you do not move bodies no
yeah ok that's about what i expected
an example is using a kinematic body as a moving platform, it can push the boxes that rigidbody ontop but it cannot be pushed by other physics bodies / affect its movement. It will phase through static colliders tho
hey, i got a problem when gameobject is shot, the material on slot 0 should change material. at some reason particle system works fine, but material is not
using UnityEngine;
using UnityEngine.Events;
public class ScreenShootable : MonoBehaviour, IShootable
{
public Material brokenMat;
public ParticleSystem brokenParticle;
public MeshFilter currentMesh;
public MeshRenderer currentMeshRenderer;
[Header("Events")]
[SerializeField] private UnityEvent onShot;
public void Start()
{
currentMesh = GetComponent<MeshFilter>();
currentMeshRenderer = this.GetComponent<MeshRenderer>();
}
private void Reset()
{
}
public void OnShot(RaycastHit hit, Gun source)
{
Material[] materials = currentMeshRenderer.materials;
currentMeshRenderer.materials[0] = brokenMat;
currentMeshRenderer.materials = materials;
brokenParticle.Play(this);
onShot?.Invoke();
}
}```
materials[0] = brokenMat;
oh thanks
how do I apply post processing to ONLY ui in URP?
this is a code channel, try #💥┃post-processing
Is there a way to make a functional DPAD for all these functions? I tried making invisible buttons to perform the actions, but it didn't work
Yes
those are not gonna be relevant then
what are you trying to achieve? https://xyproblem.info
are you asking about onscreen controls for mobile
Yes
pretty sure there's an entire onscreen button/joystick thing you could use, try googling about that
I have a joystick installed
But the game itself needs to be for DPAD
you can probably use 4 onscreen buttons then
anyone knows Why isnt my Enum isnt showing up?
Im using a class as an container
and calling it in an Array
You've only defined an enum type but there's no variable that uses it
You have to add something like public Direction dir;
its working now Ty
Has anyone here actually made an impressive project out of spamming "If bools"? Whenever im done with this current game in the future id like to try it because it sounds interesting even if its super memory inefficient
My friend told me it would be possible to even make the entire Hearthstone game with If bools (aside from the visuals) which sounds nuts to me
Not sure if you're trolling us or your friend is trolling you
I mean he is kind of a 'veteran' programmer and didnt sound like he was trolling
Filling your code with if statements is the Yandere dev meme which people usually invoke when talking about bad code
it's possible. doesn't mean it's practical
every logic structure boils down to a branch or jump anyways
it's possible in the computer science sense, not the software engineering sense.
Whats the limitation, is it too many bytes, does it make the stack super slow?
both of those are irrelevant
the limitation is it's impossible to read and keep everything in your head
yea i guess thats a more immediate problem lol
it doesn't reflect more complex logic patterns, so you can't utilize those to make it easier to comprehend
It would be AWFUL to read
readable code is super important
There's a running joke of people coming back to their project after 1-2 months and not knowing wtf their code is
tbh after 2 months even with documentation its a nightmare
Video player plays the video looped, until i need to disable the gameobject, and when enabled again - the video doesn't play again. In a script tried to prepare and play - no effect. Why is that?
Hey guys I have a problem.
I deleted the C++ file that allowed Unity to open my projects.
I dont remember which version to download to get it back.
can you not just reinstall the editor/hub if you corrupted it
The hub isn't corrupted.
Its just some file is missing which prevents it opening a unity project.
i dont think anyone can help you with that one lol
reinstall the unity editor
i dont understand what i did wrong on line 35 when following this tutorial 😭 its copied word for word
but is it copied letter for letter 🙂
you're looking at the wrong place to see where you copied wrong 😉
-# hint: look at the declaration and your other uses of that variable
that sounds like a corrupted installation to me
That doesn't look the same as the video to me fam
where's digi to update the counter...
"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: 203
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2026-04-13
thats on line 29 which is what i have on line 29
This is the video line 29
yours is not the same
and through context we can infer there is also another line that is not the same
And from this error etc we can tell that there's at least one other line, higher up in the file, that is also not the same
my error is on line 35
And we're telling you to just copy the video exactly
and it will work
not just on line 35
but in the whole file
we're not saying the issue is on line 29. we're pointing out that you haven't copied the tutorial exactly
i have
your line 29 is different, but it doesn't error, because you have another line that is also different
you have not
casing matters.
go back over the whole file. You copied it wrong earlier on and now you're paying for it.
this is like a rite of passage for beginners ngl
Is there any way I can get around needing a Return for each outcome?
Im trying to make it so the rooms can't Back to back spawn
but when trying to restart the selection proccess it still requires a return
which if I give it 'NewRoom'
its gonna do the same room anyways
if I return 'GetRandom()' then it causes a stack overflow
I tried making a Vaildator fnction but it essentially moves the problem
The function definition that you've set requires something to be returned of type GameObject - so yes, something has to be returned. You can try returning null if anything but it would depend on your needs
You've assigned it that very same value the line before so that if statement will always be true
Also, recursively attempting to select a different random room isn't favorable. Instead, maybe have some sort of secondary collection with your values that you'd simply randomize and iterate to select random rooms.
An example of what I meant, where you'd then simply iterate the collection. Note that this example would have every element selected at least once etc.
There are other approaches, if duplicates or other constraints are necessary.
The first loop simply populated the array. Second loop did the shuffling.
Assign to a result variable in the branch.
One single return line at the end
Oh sorry I'm answering a structural question but you have a logic issue too
Shuffling a list is a much better approach
I have it like that so I I can give direction values so It knows better to not circle in on its self down the line
thanks for pointing that out
I needed to check in the if statement if the New room was like the last
but I was Checking the new with the new:')
var oldRoom = newRoom;
newRoom = PossibleRooms...
if (oldRoom == newRoom)
...```Relative to your previously shown code, fixing the if statement could be done so by caching and comparing the new vs old.
is unity lighting system just buggy?
i just had my entire lighting system completely stop working until i duplicated all the objects
no
then what just happened
not sure
i assumed i messed with a value of them
but ctrl+d fixed them
so 1:1 of the original object
we'd need more details in something like #1390346776804069396
so Shuffle my possible rooms array?
You would normally shuffle a copy of your collection but if you've only got four rooms, it probably isn't worth it to do so.. Just copy the collection and modify the new collection to have the previous element moved to the first element or something so that you aren't able to select it again. Note that this would eliminate the first element as a possibly target on first use.
I've got to run, good day.
good day
what am i doing wrong now 💔
i'm guessing you didn't misspell the word in your own script
i.e. you write int remaining; (or something similar) elsewhere
rather than int remanining;
wait i see it now
What's the error say
you should certainly pay attention to the exact error you're getting
i fixed it dw
yep will do 😭
I can't when I download the installer it won't start because its still missing the c++ file.
What C++ files? There's no C++ source code included in unity editor.
What file
explain what you actually did
@polar acorn I deleted a C++ redistrutable file that was on my pc.
So, reinstall and it will be back
Give me a moment I wanna copy and paste the error I got last time.
This is the error I get.
Wait I think I got fix for my problem.
Have you restarted your PC
YEah
Clear out your temp folder and then try again
also make sure you actually have space on the C: drive
Is there anyway to check if the needed amount of space before installing?
Should be written somewhere when you install an editor version.
Guys I fixed it by switching to the latest Unity version.
so you got a new editor, literally the thing we've been telling you to do?
Look I tried installing a new Unity but I didn't have space. What happened is I had to uninstall the old one and use the new one I already hsd.
Like I literally showed you guys the error message i got when trying to install a new unity.
I was trying to do what you guys told me the whole time it just wasn't working.
#🔀┃art-asset-workflow , this is a code channel
Guys how to resize a sprite for a top down square tilemap? Idk why when i drag the sprite in the palette and select it, the sprite is smaller than the squares on the tilemap. I want the sprite size to be the same as the square size
#🖼️┃2d-tools, this is a code channel
Ok sorry
what is your workflow when creating scripts? Since I am not good at coding I create the base with no variables and logic and write down to do's and I figure out how to make that logic happen. for example here I am trying to make a interaction with NPC, signs, objects and more ```cs using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerInteractor : MonoBehaviour // On Player, is checking if interaction is possible
{
// Variables
public void OnInteract(InputValue value) // Is called by the Input System when "Interact" button is pressed
{
if ()
{
}
}
}
/*
To Do's:
- when interaction button is pressed, check the interaction
- make the interaction possible if theres actually an interactive object in front
- if the object is interactable, check what type of interaction is needed (NPC, Sign, Object, Item, etc.)
- read the information stored on the interactable object (name, text, image, etc.) and return it to this script
- Display whatever was returned as debuglog
*/``` how would you do it? is that a beginner friendly way or am I overdoing it?
that seems about right
great to hear that im not a complete idiot 🙂 now I know that the right way to do that is raycast, but I never worked with then and dont know how they work. My idea is to give the player a cube that has its collider set to trigger and the mesh renderer off, so i can use that as the detection zone for interactions. would that work?
so I can see the trigger area if I want to. boxcollider on their own are invisible and hard to debug espacially in game view
if i have an actual box i can see whats goin on
you can draw debug and gizmos and such as well, you don't need the meshrenderer
boxcolliders have wireframes when selected as well
how do I do that? The wireframe of the colliders are only visible if i klick the weird green edit button but in the game view theres no colliders visible
should be able to see them in scene view
do I have to enable something because for me they are not
are gizmos disabled?
oh... yeah 😅 😭
Guys what's the best way to create a 2d platformer? Tiles or just items? And if we consider tiles, how to create tiles with a collider/rigidbody/scripts and other components?
Im talking about 2d
there's no "best", there are many working ways
Where are they pinged at?
for tile collision you can use a tilemap collider+composite collider
I would use the interface for this
Why 2 colliders
the composite merges individual tile colliders together so there's a uniform surface
Oh so basically if i have 3 tiles in a row i can use composite collider to group them?
not really what i said
the tilemapcollider will already make collider shapes for each tile
the composite collider merges the shapes together
this isn't about grouping tiles
both of these colliders would be on the tilemap, not individual tiles
Hmm i'll go check tutorial to understand better
Ty 🙂
@naive pawn just another question, can i have separate things made of tiles that behave in a different way? For example a level with a platform composed by 4 tiles in a row and then a square with 2x2 tiles that moves up and down?
Can i use same tiles but different colliders for this?
they'd have to be on a separate tilemap if you want separate colliders
or just make it a regular prefab and apply it with the prefab brush
they won't be traditional tiles though
Ok
I have a problem with not being able to stop a moving object. I would like to post the code snippet here but i dont know how to create the little code window.
!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.
if (cueBallRigidbody.linearVelocity.magnitude < 0.2 && hasBeenHit)
{
cueBallRigidbody.linearDamping += Time.deltaTime * 0.3f;
if (cueBallRigidbody.linearVelocity.magnitude < 0.02f)
{
cueBallRigidbody.linearVelocity = Vector3.zero;
hasBeenHit = false;
cueBallRigidbody.linearDamping = 0;
gameController.OnCueBallStopsMoving();
}
}
velocityText.text = "Velocity: " + cueBallRigidbody.linearVelocity.magnitude.ToString() + ";Has been hit: " + hasBeenHit;
this code is in my update function. I also have this debug text, which let me know that the ball is not instantly stopped when hasBeenHit is false. It sort of jitters around for a few seconds before stopping
i also am applying some damping at this low speed to simulate how a ball rolling on cloth stops when it has lower speed
what's the actual question here
why is it not instantly stopping when reaching the threshold
Isn't it rolling?
yes but i have it so that the speed will gradually decrease
rolling is angular velocity, not linear. So it's going to keep a bunch of energy even if you are setting the linear velocity to 0
the rolling then will give some linear velocity back due to friction (because that's how rolling works)
long story short - if you set angular velocity to 0 too it will stop faster
if (cueBallRigidbody.linearVelocity.magnitude < 0.2 && hasBeenHit)
{
cueBallRigidbody.linearDamping += Time.deltaTime * 0.3f;
if (cueBallRigidbody.linearVelocity.magnitude < 0.02f)
{
cueBallRigidbody.linearVelocity = Vector3.zero;
cueBallRigidbody.angularVelocity = Vector3.zero;
hasBeenHit = false;
cueBallRigidbody.linearDamping = 0;
gameController.OnCueBallStopsMoving();
}
}
it still goes backand forth between the hasBeenHit variable being true and false
even after setting the angular velocity to 0
hasBeenHit is a totally separate thing. You haven't given the full context on that
i have no idea how it gets set to true
if (Input.GetKeyUp(KeyCode.Mouse0))
{
cueBallRigidbody.AddForce(shotPowerAndDirection, ForceMode.Impulse);
changeCamera();
//start decalarating
mousePressedTime = 0f;
hasBeenHit = true;
}
``` It gets set to true when i apply a force "hit" the ball.
if this is the only place you set it to true, then you must be releasing your mouse
otherwise - you probably forgot about somewhere else it's being set
it gets set nowhere else. i will try to do by pressing a keyboard button instead
but you're seeing it get set to true in your debugging?
If so you must be mistaken
I'd also recommend using Debug.Log instead of an in-game UI element, you'll get more information like the full sequence of events.
try adding a debug log to where you're setting hasBeenHit
okay yeah now it shows it has been set to true twice
stil dotn understand how this can happen since getkey up only runs the frame that the key gets lifted
make sure you don't have more than one copy of that component in the scene
if it's called in fixedupdate, then step can happen several times over the course of a frame
that's unlikely though, unless they are getting sub-50 fps. but it also wouldn't be as consistent
right click the script in your project folder and select find references in scene
see if you get more than 1 hit
is the problem that i am referencing this game object by doing:
public GameObject cueBall;
```?
this would seem to indicate that you have it set to true twice, then you set it to false twice.
the second time you set it to false shouldn't happen, if it were on the same component.
do you perhaps have multiple components of this same type?
try adding a context to your logs (eg Debug.Log("...", this);), then check if each of the logs are coming from the right object
well, you generally shouldn't use GameObject as a type, and instead use the component you care about (which seems to be Rigidbody in this case), but it shouldn't cause an active issue
yeah i had the script set to two different gaem objects one being the camera and the other being the actual cueball
now it only sets it to true once and stops it moving once
i actually have no idea how i managed to do that
Thank you
however its still needs some time to completely be set to 0
from here on its zeroes
i have a lot of "the referenced script (unknown) on this behaviour is missing" warnings
is there a way to fix them without messing the scripts
did you do something to cause that, like moving .meta files (or not moving them)
yeah i moved my scripts and folders
did you move the .meta files as well?
well that would be the problem then
is it difficult to fix them?
if you're using version control, it's really just a matter of reverting to the last good commit. if you're not then you need to check to see if the old .meta files are still available and move them to the right place. if they aren't then you need to fix the broken objects manually
can I use unity version control instead of git? not that familiar with version control and wanna just get it set up quickly (forgot to set up git at start of project and getting a headache with lfs)
You can use whichever one you want. That's why it's there.
awesome, thank you
I might be making progress with LFS, but ive a feeling something will go wrong lol
Hi, i am a beginner and im having a problem with calling a void which belongs in a game object, being called from a prefab as i cant make a reference. Ive tried using static but i cant get that to work either, what should i do?
can you clarify what you mean by "cant make a reference" ?
what is it specifically you are trying to do
how are you trying to do it
and whats happening, vs what is supposed to be happening
sounds like you need to pass the reference to the instantiated object
https://unity.huh.how/references/prefabs-referencing-components
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
<@&502884371011731486> spammer
?ban 1374720700363051122 Ignoring warning for off topic
zi_danee was banned.
so i have a prefab which has already been spawned in the same scene as a gameObject. When the gameObject collides with the prefab, a script within the prefab needs to call a void subroutine in the script of the gameObject. However since it is a prefab, i cannot make a reference to the gameObject im pretty sure. I have tried making the void subroutine a static, but i cant get that to work either.
of course you can make a reference with the gameobject, you just need to use that instance of it
since you are working with collisions you have a simple way of doing it
you don't need a persistent reference, the collision will give you access to the object's collider which you can call GetComponent on
you can do something as simple as
void OnCollisionEnter(Collision collision)
{
// make sure whatever you hit has the script you need to call
MyGameObjectscript targetScript = collision.gameObject.GetComponent<MyGameObjectScript>();
if (targetScript != null)
{
// call whatever you need to do here!
}
}```
or use TryGetComponent which combines those two lines into one call
thx
the void im trying to call is push which is in Birdscript and this is written in PushScript but it isnt recognised? -ignore if the trigger stuff is incorrect
What is push in this script?
it is the void subroutine im trying to call located in Birdscript
Is this OnTriggerEnter2D in Birdscript?
no this is in PushScript
You can change time scale to 0 and this will "freeze" many things but the program is still running
How
Oh ok
You're trying to call a function on this script. If you want to call it on a different object, you'll need to actually call it on that object
I'm just gonna follow the brackeys tutorial
Do you have a reference to the Birdscript you want to call this function on
not yet, this was what i was trying to work out
Can any Jetbrains users confirm that it has different "problems" spotted than VS code? Jetbrains brings up lines of code not being used by anything, problematic namespaces etc that i do not see in vs code
Which Birdscript do you want to call it on
can you show an example?
im confused
You want to call a function on another object. Which one do you want to call it on?
oh, Bird
Is it always a specific object that exists in the scene before you start play mode
i dont see these kinds of issues in code vs
im pretty sure
So make a public or serialized variable and drag in the reference
different IDEs usually have differences in what they highlight. you could probably configure the specific warnings if you don't want to see them
these are just warnings though to help with code quality
I am psychologically a perfectionist even when its objectively worse. This is bad, bad
should have stuck with vs code
🤷♂️ disable the warnings and it'll be good again. its made to follow a specific standard, you dont need to follow the standard. everyone likes their own style in some way
If these are just typo errors and stuff is there a way i can just easily transfer this to an AI or something enmass
I cannot be assed to go through like 500 files like this
the "Namespace does not correspond to file location" is not something people commonly do in unity regardless
you dont need to go through 500 files lol, just hide the warnings or pretend they dont exist
usually your IDE would have some kind of autofix button though. Like at least in visual studio i remember there was a keybind that'd clean up the file and would automatically fix spacing + remove unused usings which is what most of your warnings are
Also it suggests names starting with _ which i personally hate using. You shouldn't change your whole style because an IDE has a small 20x20 yellow triangle
I'm having problems with github, does someone have some free time to help?:))
ask away
Just ask your question. Nobody is going to dedicate their time to a problem they don't know anything about.
mb
I'm merging my branch into the main branch
and my colleague is doing the same
but when we do that, some of our scenes, prefabs, sprites, etc; dissapear
and we tried to merge again, and nothing happened
we've been here for 3 hours trying to figure this out
Are you editing separate scenes/prefabs/assets and they still disappear?
Are you committing the meta files properly as well?
yes to assets and prefabs
no to scenes
but even when i deleted the scene on my version, the main version had the same problems
Problably not
How do I make shure that it is commiting properly?
as a jetbrains user this also happens to me as it introspects the entire project including packages you import with its own opinionated warning system
you can really quickly get rid of those, though, and if you get used to it it can be extremely good. I don't know how you live with VSCode honestly, I've never had good intellisense there
is .meta in your .gitignore at all?
let me check
sorry if this problem is too obvious, it's my first time using github
I'd suggest that you and your colleague watch some git tutorials for half an hour instead of trying for 3 hours to find it out yourself (i'm not the best person to know about this though, lol)
from what i've heard, merging can generally be a nightmare sometimes
Hi I'm new to Unity and I've been crashing out for 30 mins because my gun rotation isn't working, I was wondering if anyone could help me out with a quick solution since ChatGPT is wasting my time with solutions that don't work.
I took this model, and my gun is following where my mouse is, which is fun but since everything is pointing right as a standard (the gun also moves up and down with my mouse), it would only make sense that when my mouse goes on the left side of my character, my character flips and looks to the left while also pointing my gun to the left. For my character it works perfectly fine but my gun also kinda mirrors but it's upside down instead of mirroring. Not sure if I can also share my code since it could make my message very long.
Yeah that's smarter
Well, you shouldn't try to modify the same assets/prefabs at the same time. And definitely not scenes. It's not impossible to solve merge conflicts with them, but it's hard.
Im not sure what you mean by deleting the scene and the main having the same version...
It sounds like you're rotating the gun around the player that naturally makes it flip upside down, unlike with the player where you just reflect it. Maybe try the same sort of logic with the gun, where after it goes to the left to the player it flips over the Y axis as well to appear normal
In unity project every asset file has its own paired .meta file. You can see them if you open the project in file explorer. These carry important info on the asset and need to be committed.
Basically we were working on different prefabs and I deleted the scene that was no my colleague's branch
You intentionally deleted a scene, but it was not synced(deleted) on main?
Or you didn't explicitly delete anything, yet it was gone on your colleague side?
Which one?
i wasnt remembering the exact process
I just tried to open the main again
I'm having this problem now
That means that the scene asset ID has changed. What likely is happening is that you and your colleague created these scene independently OR did not sync it with each other initially, so it was basically 2 separate scenes with the same file path - the ID is different. Then each one of you kept on committing the id that is correct on their side, basically breaking the project for the other person.
Oh://
At least that's one plausible explanation
The seconds options seems to be what happened
Is there some way to solve this?
Since we both have important things on our scenes
I'm no expert so this might be wrong, but you could both rename the scene as something else so you can merge it and have 2 versions, then manually go in and stitch things together
We did that but it had problems again://
I gtg now
Its pretty late here
I’ll be working tomorrow with a fresh head (no so much since i have to publish the project tomorrow as a school project)
Thank you guys for your time and patience to be here helping us!
Have a great week bye!
I appreciate the quick response but it hasn't really helped me any further. Maybe my scripts can clear up what I'm dealing with
I'm using PlayerFlip to handle the player's visual orientation left or right based on the mouse position relative to the player.
And PlayerAim rotates the weapon toward the mouse position so the gun always points at the cursor.
at this point I have absolutely no clue on how to fix this annoying issue. ChatGPT keeps telling me to seperate body flipping and weapon aiming completely by only using PlayerFlip to mirror the character visually and PlayerAim to rotate the weapon in world space without any additional flipping or scale changes but eventually leads me to an issue that's even worse or that's just messing everything up
oh I didn't see the messages above, continuing this ^^^^
It looks like you're scaling the player to something like (-1, 1) when facing the opposite direction, but only rotating the gun around a circle around the player. When you're flipping the player, it's only that sprite, not the gun within it, because of localScale.
The problem is (And tbh id really like to find a redeeming factor of these kinds of jetbrains features) that this stupid ass software detected some of my unfinished planned architecture as code that should be deleted because nothing referenced it yet etc
I am sorry thats just absolutely braindead software design
You intentionally have unfinished code that isn't referenced and it's warning you of that, you can ignore it, that's why it exists. It's not saying it should be deleted, exactly, rather just notifying you that it might be unintentionally there.
Right but i thought the appeal of jetbrains was its error identification feature and code cleanup. The software just nuked half my project
If you really hate it, then you can suppress the warnings by marking the files to not be introspected: https://www.jetbrains.com/help/rider/Code_Analysis__Configuring_Warnings.html#exclude_items
It has functions built-in for code cleanup and you likely triggered one of them, CTRL+Z with git or Jetbrains' local file history (google), mark the files to not be introspected, and continue
sorry, accidentily deleted it
You can use #🔎┃find-a-channel
i guess i wont give up on jetbrains yet then, thank god i regularly archive my builds
I'm wanting to make a private VR Chat world from KH3 to make Kingdom of corona
Likely what made you get frustrated will turn around and become a great feature for you- its code cleanup and refactoring capabilities. When harnessed correctly, it's saved me a lot of time with renaming stuff and removing old code.
#notsponsored i even only have the noncommercial version right now
I looked, but those are more for advertisement questions, oor how to improve the server questions.
#📑┃channel-directory? (i'm also new here)
Are there any VRChat-specific discord servers? Like, what exactly are you looking to ask here?
I create VR chat worlds with unity, but I need help finding assets and map rips
this server does not help with VR chat or mods, please find a VR chat specific server
not mods, assets
For assets there's http://assetstore.unity.com/ or any Unity assets you can google for, not sure what you mean by map rips
map rips are just assets/worlds taken from a game to use in things like Unity
I don't think you're going to find those here
Basically steal other people's work. We don't support this topic here.
Oki, sorry for wasting your time. I'm only 16 and my mom doesn't want me spending money on assets. Sorry again/gen
https://www.kenney.nl/assets has a lot of good free assets for beginners
Okay My Little Pony actually helped me out more than you think. Now it works exactly how I wanted it to. What I did was add this script WeaponFlip to my WeaponPrivot.
Thank you for your time <3
Hello! I'm really struggling trying to understand the concept of event handlers, I'm currently following a 10 hr course of making a game (CodeMonkey) and I'm really confuse as to why certain codes exist and what it does. This is the current which works too.
!code it also helps to actually point out which specific code you don't understand
📃 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 must ask what's the point in the code websites when the .txt files work fine? especially when half the websites are broken
Also it's much easier to be able to view long blocks of code in another tab and be able to refer back to it
tf your's look much different than mine
Oh, I didn't realize that's how it looks like
that's a mobile screenshot and is how it always appears on mobile
ahh guess that kinda makes sense but both the functional websites absolutely suck on mobile ~_~
the other point is fair though
no line numbers and it gets cut off at like 50kb
Sorry ! I don't really know how to use those websites. First time here and really desperate too.
paste your code in, save, copy the link, paste the link here
if someone pasted a 50kb file of pure code here i would tell them they are on there own lol, the no code lines i can see as a bother though
oh and you can't properly view multiple files together, gotta reset your scroll every time you check the other file
also you can't do other stuff in discord (asking for context, answering other questions, answering unrelated chats) in the meantime without resetting scroll
also no search
also no folding
a powerful website for storing and sharing text and code snippets. completely free and open source.
it also helps to actually point out which specific code you don't understand
you never specified what the problem was other than "struggling trying to understand the concept of event handlers"
(prolly my fault)
Sorry! I don't really know what question to ask because I don't really understand it well myself. I only understand that it's good for decoupling, but I guess i'm struggling to read and understand it?
so im noticing that use of EventHandler and i don't think ive seen people use those before.. you can typically just use simpler delegates, especially given that you aren't using any of the passed arguments
having an Action<Vector2> would probably be simpler and more direct data flow
could you be more specific as to which part you're struggling to read? if there's like, a specific line or block, we oculd explain that
otherwise it's kinda hard to help a vague question
So GameInput.cs, Awake() block, how does playerInputActions.Player.Interact.performed += Interact_performed work?
the += there is a subscription
the performed is an event
when you subscribe, you're telling it to also call that function when the event fires
it's like assigning a method that should be called, but it's += to preserve any listeners that have already subscribed
So, when I press interact, it performs the function Interact_performed? And what does the OnInteractAction?Invoke do?
Invoke is firing the event
firing is a new one
cant tell if you mean calling it, or fire like what an employer does (ie unsubing it)
the ?. makes it not do anything if it's null, which it would be if nothing has subscribed
So in player.cs, GameInput_OnInteractionAction is listening to that event?
it's listening to OnInteractionAction, yeah
I see so it's like a red light green light thing? Press a button and it goes green and everythign thats looking at the light will do their own thing?
Sorry I learn from weird analogy way
you could imagine it like that, sure
Okay I kinda get it now, thanks !
hmm that analogy feels maybe more like polling
could say it's like making a post or sending a message and whoever's subscribed gets a notification
That's a better one 😆
You'll quickly memorize relevant code and syntax over time as youre typing it in real work. Copy pasting it from a file isnt going to help you memorize it
Though if you find it easier in terms of accessing quick notes or links to documentation, then sure.
maybe if i learn stuff like input
I should type down what getkeydown or getaxisraw etc..
Usually youd just go to the documentation anytime you need a refresher on what stuff does
It'll likely just take you longer to find your notes file compared to googling getkeydown unity
Idk tbh
Like yes the code is explained if i left click it but i don’t really know where to search in the first place without googling
Then work on googling skills. They'll come as you code more and need to find stuff in documentation
If you have no clue at what the class or methods would be called, google a high level concept of what you want to achieve + the word unity. You'll find results
what exactly do you mean?
you mean for UI elements?
you mean the default axes? those aren't ui stuff
you can just check in your input manager
Well, technically all inputs would be part of UI, not GUI though. I agree it isn't very clear what is asked here
by "ui" there i'm referring to ui elements like sidia asked, i couldve been clearer 😓
i want my enemy to move around the player but i don't know how to calculate the angle for the enemy to move left or right
X = Cx + (r * cosine(angle))
Y = Cy + (r * sine(angle))
could you be more specific about what you want the enemy to do exactly
oh i found the solution. nvm
i just want to set my enemy position based on an angle with the player as the radius point.
So I am a little confused with the parent constraint component
I wanted to spawn a thing and attach it to the body part
anyway the point is it spawns properly, in actually behave like it's attached, however, the moment it gets attached it changes it's rotation in a way I don't expect
ParentConstraint constraint = stickie.GetComponent<ParentConstraint>();
constraint.rotationAtRest = stickie.transform.rotation.eulerAngles;
constraint.translationAtRest = stickie.transform.rotation.eulerAngles;
constraint.SetSource(0, new ConstraintSource{sourceTransform = assumed_hit_hitable_part.transform , weight = 1});
constraint.locked = true;
piece of code I expect to work
I am probably misusing the component
constraint.translationAtRest = stickie.transform.rotation.eulerAngles; this is definitely not right
translation is an offset in position
what behavior are you expecting and what's actually happening?
midnless happy copypasting coding failed me again
I will attach a small video in a minute
it kinda works
when arrows were children it was better
but I don't want to fiddle with them actually being children
I think I am starting to get it
ParentConstraint constraint = stickie.GetComponent<ParentConstraint>();
constraint.SetTranslationOffset(0, assumed_hit_hitable_part.transform.InverseTransformPoint(stickie.transform.position));
constraint.SetRotationOffset(0, (Quaternion.Inverse(assumed_hit_hitable_part.transform.rotation) * stickie.transform.rotation).eulerAngles);
constraint.SetSource(0, new ConstraintSource{sourceTransform = assumed_hit_hitable_part.transform , weight = 1});
constraint.locked = true;
way more inconvenient than I expected but it works
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
return ItemCosts[itemID];
item costs is a dictionary how would i parse it using a number
Like that
but
Argument 1: cannot convert from 'int' to 'string'
sorry should have sent that at the start
So your dictionary is keyed off of a string, not an int
Guys how to DEFINITELY delete a tile in my tilemap palette?
2d of course
Idk why a pink square appear
so is c# not like python where you can sort through dictionarys using numbers you have to use the key?
Python doesn't do this either
To access a dictionary element, you have to give it a key
You choose what type that key is
You've chosen string
oh ok i understand now i was thinking of lists
C# has lists as well
yeah but for what im doing a dictionary is easier
Guys how to DEFINITELY delete a tile in my tilemap palette? Of course im talking about 2d. Idk why I have a pink square on my palette, i tried to delete the sprite.
hows this a coding question ?
Umm sorry? Calm down
I mean, you're the one in all caps and reposting the same off-topic question so maybe you ought to be the one to calm down
You're not getting answered here because it's not a coding question
That's a better answer
It's the same answer
I mean less rude than the other one
get over it
It's a matter of education. nvm
Has anyone used Obi Rope?
I want to extend the rope based on a rigidbody dynamic attached to the end particle via particle attachment. The ObiRopeCursor supports extending, but its just length rather than actually following the pull on the end of the rope
whats an alternative to ckeck for grounds using rigidbody? cs // ground check isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance); depending on the terrain or the players mesh i need a different distance. is there a reliable way or do I guess the value until its working?
could have a second longer raycast that decides the distance for the ground check based off the type of ground beneath it
doesnt make any sence...
I will still need to guess
were you not asking how to handle different terrains for the ground check (assuming they need different values, for whatever reason)
of course you are going to need to test values to see what feels like the best for the distance of the ground check
Why not just do one raycast and check its distance
yes kinda, but in that case you described i have on raycast super long which is checking how far the ground is and puts that value in the raycast for the isGrounded check but that doesnt make sence sinc i have to limit it somehow and there the guess work begins again#
You can detect a raycast hit, but do nothing if it was too far.
RaycastHit.distance
So just do one raycast with the max distance
Or I'm majorly missing something here
i think i misread what they were asking
It's not super clear what theyre asking
I have a mapping system that charts out my movement by making line renderer points and all that good stuff.
But I am having trouble dynamically rotating the map based on the player's rotation such that up on the map matches player's forward.
It's a world space map held on a device in hand. There is also an issue of rotation on all axes since this is about diving and I can orient the player in any way.
This is tripping me up
it isnt, i read what they said as "i have multiple different terrains and each one has it's own distance for the ground check that feels the best. How can i know which value i should use for it if they are all different"
but even then yeah one raycast that's just long with a value to see if the distance is less than would work
for now I have a capsule player so the ray distance should be somewhere between 1f and 1.2f but that changes when i add a different player
You can use OnDrawGizmos to draw the ray so you don't have to guess but use your eyes instead
(Or OnDrawGizmosSelected probably)
never used ondrawgizmo so I dont even tnow where to begin making that happen 😄
docs, generally
then have the value synced to the character chosen or do like most and keep the collider a sphere cast (think the main time this isnt done is fps games) and just adjust the visual height of the character
Most unity docs have small code examples and explanations that should get you started
fun fact, unity has built in Queries/Casts gizmos built in the Physics Debugger
That's true, though I meant more for tweaking it in the scene view/prefab editing
@stuck parrot Magic has a point too, you could always just have code that calculates the ray origin from the character's collider values
I also usually prefer spherecast, not raycast
sounds goob but I dont know how to do that
Like what if you are standing on a tiny gap and the ray goes through that?
Now it thinks you are in the air even tho youre not
can I just add an empty as a child of the player and add a box collider set as trigger underneath the player? this way I can control it and actually see it. by the way OnGizmoDraw doesnt seem to work for me ```private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Vector3 origin = transform.position;
Gizmos.DrawRay(origin, Vector3.down * groundCheckDistance);
Gizmos.DrawSphere(origin + Vector3.down * groundCheckDistance, 0.1f);
}```
you have to have Gizmos enabled for OnGizmoDraw to work
I do have that
check what I suggested earlier, use the physics debugger enable the queries tab and check what it shows there. must be in playmode tho for that iirc
how do I enable that physics debugger? whats a querries tab
Window -> Analysis -> Physics Debugger
I enabled all but I dont see anything. But back to the jumping, is raycast a good practise or should I use a small box collider underneath the player? That way tiny gaps in the terrain would not cause issues
raycast is too thin, generally thats either done in multiple spots around the capsule or a thicker one like overlap or spherecast etc if normal/rayhit of surface is needed
using colliders is the worse method imo
you can make raycasts thicker? also why are colliders a bad method? I see only benefits in them. you can see them unlike raycasts and you keep the code clean by giving the script/logic to that object and not the player
You can see casts just fine, you're clearly doing something wrong
raycasts can be made thicker by using a different shape instead of "RAY"
ray is just a line
boxcast, spherecast etc
good to know, are raycasts only "shot" when for example I press jump or are they there all the time?
they're "shot" when you tell the physics system to "shoot" them
void Update() {
Physics.Raycast(transform.position, Vector3.down, maxDist);
}```
the physics system has no knowledge of you pressing jump
but I could just theoretically make the raycast only happen in the OnJump method? that way I would safe resources? (I dont know how much computer power raycasts take)
doesnt work for me 🙁
I found out that if the ray I cast is negative (above capsule) it IS actually visible, but not if it is cast down
don't worry about resources at this scale
is it perhaps obscured by other objects
uh hm i guess debug stuff would be drawn on top
so hopefully that wouldn't happen
anyone know this por favor?
have you tried extending the distance a ton?
do you have a more specific question, eg an issue with a current implementation, or a question about transform methods? as it stands it's kinda vague what you're looking for and hard to answer
I also figured out why the physics debugger didnt show anything the first time. I didnt knew it has to stay open, tought it was just settings
