#š»ācode-beginner
1 messages Ā· Page 178 of 1
async Task
is there a way to check if an application has been opened for the first time? like i want to set playerpref defaults or volume defaults or something
IEnumerator is C#, iterating them automatically is a Unity thing.
bingo
List<IEnumerator> stuffToCheck;
void CalledRegularly() {
foreach (var item in stuffToCheck)
item.MoveNext();
}
it also needs to remove items that are exhausted, but that's the idea
You can use Playerprefs
you can test if the playerpref keys exist at all
in fact...
Like getint with default value 0 and after first open set that int to 1
Oh yeah, getkey also works
then your game will wind up saving the prefs later
using singletons has been great so far, it means i dont have to keep loading a loadscene with ddols on it
and bam, you've got default values saved
idk if u told me this
some of my singleton monobehaviours live in DontDestroyOnLoad :p
i was just working on that a minute ago, actually
I have per-scene singletons that handle a single game session
and then eternal singletons that handle the whole play session
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/qujopicite.cpp is this okay for setting the score
still, i have discovered magic of singletons
Yeah, that'll do just fine.
Why cant I add that public static int
it cant find score even though its public
you can't access a static field through a specific instance
static hell
either make the field non-static or don't reference a specific ScoreScript
avoid static for this
someone can help? with my code? i need to show checkpoints sequentially when you collide with them
I'd rather have a static reference to the ScoreScript than a bunch of static fields on the ScoreScript
show them ?
cs
wait but then how will i make it so every object that has the score script has the same score?
can we play with sprite editor via code? I want to move each square 16 pixels to the right
cant reslice cuz animations already linked to them š„¹
make it a singleton also this
#š»ācode-beginner message
https://gdl.space/ehepiqepof.cpp here is the scrore script after the changes incase you need this
If everyone has a reference to a ScoreScript, then just make the field non-static
A static field is not attached to a specific object. It's stored in the class itself.
i feel like we're doing circles
you should watch some basic c# & unity tutorials
kinda hard to explain things to you
Therefore, it is inappropriate for something that each instance of ScoreScript should have its own value for
please
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
here
ok and whats the issue again ?
you can create a seperate script that can be accessed by any script that uses the score variable. Use this new script to store the players score and pull the score value from it when you wanna display it. Write a function in this script that updates the score to the new score you desire.
thats how my peewee brain thinks this could work if you aint found a solution
here for not spaming the same
What do you mean by show them
appear, not show
what do you mean by appear
its the same thing

maybe stop letting gpt write your code it be easier for you to explain the problem
oh no, another chat-gpt enjoyer?
this time in spanish !
even better š
Portuguese
for example, when you collide with the first checkpoint, the second checkpoint appears, and so on with all those that are in the parent
is this man really coding with chatGPT?
my father keeps lecturing me about how great it is for coding
you can always ask chat-gpt since he already knows yours(his) code
just move indexes through an list
and then we have every single example to the contrary lmao
its not that diffcult
the GPT code you sent its overcomplicated
and doesnt work
learn how to use Arrays
scrolling through index of checkpoints shouldbe easy as that
He doesn't do things correctly
every time I tell him chatGPT isnāt good for coding, he just tells me I havenāt used it enough myself
no shit
arguing with a brick wall would be more productive
ah so its not their first rodeo here
sherlock
talking about my father
i always have the same discussion with my brother and he ends up saying "then you are not fully using chat-gpt potential, user issue"
Oh lol does ur dad get paid by OpenAI ?
not even. but heās very tech saavy
no arguing in a few years it will be capable of some interesting stuff but 4.0 aint it yet
easier for the art ones to get better since that art doesn't require logic systems xD
Even with art it's just blatant most of the time
he got his PhD in network engineering before it was a real discipline, and heās been THE tech guy since the 80ās
well my boss just fired two 2D concept artist cuz of AI so š
All you have to do is look at lining/lighting and FINGERS
yeah thats def the first field to go since these are more practical for concept arts but not full designs / sprites /
yup
the influx in code questions that are gpt is becoming rampant
I dont think it was this bad a few years back was it on this discord
part of my fatherās PhD thesis was based on passwords being way stronger if they were multiple words. like baddog being a potent password
yea it's very common lately in here
Isn't there like a rule in here that prohibits helping with chatgpt written code? I could swear I've read that somewhere
that wasnāt the whole thing, but it was a pretty big discovery at the time
there is
but 50% of newcomers never read the rules
or more
kinda.. its not very specific on that
just says dont Post AI answers or question that are unverified
doesn't specifically say you can't help fix once you find its AI code, not that I'd want to
well helping someone who has chat-gpt generated code is completely pointless
as he doesnt even understand the code in most cases
we just need a dump AI-Coding channel
the story goes that he was TAing for a class (I assume in cryptography), and challenged students to beat the standard password-brute force algorithm. It was based on Dictionary brute force.
It defeated everyoneās password easily, and the moral of the lecture was supposed to be that passwords are not safe.
all the GPT fetishers can hang out there
In the 80s computer science was still catching up with writing down the obvious things.
some smartass kid walks up, puts in a two word password, and everything comes to a grinding halt
several years later, degree
tldr he basically studied weaknesses in dictionary attacks
Alright, so Iām trying to grasp the concepts of async await but this is really difficult for me to understand lol. So say I have a function. I want this function to execute some code. Then, I want it to wait for player input. Then, I want it to execute more code. Iām assuming for the āwait for player inputā thing to work, Iād have to use async await, but I donāt really understand how I would go about using it. I also understand that using a coroutine would be better for this situation, Iām just trying to grasp the general concept of async await with this hypothetical.
you can just use coroutines for that all you've described
WaitUntil()
true
Yes, I know, Iām just trying to understand the concept of async await.
WaitUntil(()=> Input.anyKey) iirc
on old input system only
the benefit of coroutines is that it is easy to wait into specific points of unityās event functions, in terms of timing
like WaitForFixedUpdate(), WaitForEndOfFrame(), nullā¦
did you watch tutorials about async?
Yeah, I get that, this is just a hypothetical and Iām trying to figure out how async await works
The C# async / await workflow can simplify your code and give you more granular control over your game in Unity.
Learn how to convert your current coroutine workflow, what a task is, how to run sequential and synchronous code and how to return data from an asynchronous function.
UniTask: https://github.com/Cysharp/UniTask (Provides an efficien...
that helped me a lot
make console apps with asyc task , you'll be expert in no time š
i have no actual experience on it, but my undersranding is that async just runs separare from main thread
Thank you, Iāve been looking at some other tutorials but they havenāt been too helpful, hopefully this one will help me understand. Thanks!
Async is not coupled to running in threads
he also covers things how to convert coroutines into async so it's easier to understand if you are just starting with async
isnāt it mostly a function that can run whenever?
so it could run in a different thread
but doesnāt need to
which why if you do UI stuff you usually get error
Itās an abstraction around the idea of things running asynchronously, whatever that may mean in your project
most UI run on main thread, so some framework you try to chaning UI in async and it spits error
i mean, duh. But the question is when it runs
like if you do A, async B, C. B might be before or after C. But i donāt know enough
Hello, this is my first time using the built in character controller in unity. Currently I am having trouble with making the player jump when pressing the bind. Here is my script: https://hastebin.com/share/bodufewiqu.csharp.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hi sorry to interrupt but does anyone know how to collaborate with someone on a game?
git + github
this is separate from your problem, but I recommend making an enum for current player state. Eg neutral, jumping, swimming, etc. It will make your life easier
can you do steps⦠i have unity cloud
I also made a separate class for player contact state, for things like grounding, touching left/right wall, etc. Because otherwise this shit gets real messy, really fast
just trust me on that
just get something like Github Desktop, it does it all for you
there's plenty of tutorials on it + unity. make sure you use Unity .gitignore
I need to make a better one lol https://youtu.be/5IxUElilf2M
adding a collaborator is just as easy you do it on the website
the fewer things going on inside your player movement class, the easier your life will be
as in a second class in the same script, or another script and then grab a reference too it?
This looks fine. Is the "Jumped" message not happening at all?
Ah, verticalMove is probably going down forever
Consider setting it to 0 if isGrounded is true on the character controller.
No, the jump message is working properly.
I have a separate file called ContactState.cs that defines a non-monobehaviour (POCO) class called ContactState. PlayerMovement has a field to contain a ContactState object.
you probably want a different class to have access to this object to modify it
Then? What's expected result vs what's happening?
you should generally tell us what's wrong, yes (:
so I have TileCollision (my game is based on tilemaps), which has OnCollision etc. Whenever I get collisions, I modify the contents of the current ContactState
Hey guys, could someone help me please? I dont know exactly why my character is falling like this when on the equator of a planet, this is the script that moves it:
{
if(!UseCustomGravity)
{
gravDir = (attractor.transform.position - transform.position).normalized;
rb.AddForce(gravDir * gravForce);
}
else
{
gravDir = gravDir.normalized;
rb.AddForce(gravDir * gravForce * Time.deltaTime, ForceMode.VelocityChange);
}
transform.rotation = Quaternion.FromToRotation(transform.up, -gravDir) * transform.rotation;
Debug.DrawRay(transform.position, gravDir * gravForce, Color.red);
}```
Apologies, the player says jump but isnt going, up, I'll try this real quick to see if it works.
is UseCustomGravity turning on and off?
I actually have ContactStateManager, which contains 2 ContactState objects. One for this frame, and one for last frame. Because there are a LOT of times where you want to compare this vs last frame. ContactStateManager just holds a reference to this frame and last frameās contact state. Every frame, it deletes last frameās contact state, and moves this frameās contact state to be last frame state. This way we can start populating the current state.
this is drifting pretty far away from Stick's question
#šācode-of-conduct The code could make zero sense. Folks may have to literally write, design and teach what their code does.
It's sort of necessary that the person knows what their code does or have some working/confirmed base foundation.
With a tutorial, at least we'd be able to tell them which step they've missed or verify if the final product actually works.
Custom gravity is a bool that changes between an attractor point and a manual vector for the gravity. This is the script of the editor:
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Gravity))]
public class GravityEditor : Editor
{
public override void OnInspectorGUI()
{
Gravity grav = (Gravity)target;
grav.UseCustomGravity = EditorGUILayout.Toggle("Use Custom Gravity", grav.UseCustomGravity);
grav.gravForce = EditorGUILayout.FloatField("Gravity Force Value", grav.gravForce);
if (grav.UseCustomGravity)
{
grav.gravDir = EditorGUILayout.Vector3Field("Custom Gravity Direction", grav.gravDir);
}
else
{
grav.attractor = EditorGUILayout.ObjectField(grav.attractor, typeof(GameObject), true) as GameObject;
}
}
}```
iām just giving him separate advice that might help him stay organized. I royally fucked up my player movment script when I started, and it looked kind of like stickās. I wasted weeks refactoring to sort everything back out, to be able to add features.
I want to save him the struggle that I went through
@elder osprey
also, what's the problem, exactly?
it just looks like gravity is very weak
and you're moving up and down
if you have multiple scripts using FixedUpdate, how do you know in which order they will execute
you shouldn't care about the order
You don't. Without doing a workaround and forcing the order
gotcha
Different classes can have different update orders
If you want a specific order of execution, you should have it inside single fixed update instead
Most of the time*
My main problem is that my jumping script doesnt work on the equator of the planet, and I think it has something to do with the gravity since it also works fine on the poles but doesnt on the sides. In this video you can see it better:
it looks like the jump is always going in the +Y world direction
yeah it looks like that but idk why, this is the script that does it:
{
//Vector3 jumpForces = rb.velocity;
if (grounded)
{
//jumpForces.y = jumpForce;
rb.AddForce(transform.up * jumpForce);
}
//rb.AddRelativeForce(jumpForces + transform.up, ForceMode.VelocityChange);
//rb.velocity = jumpForces; //+ transform.up;
}```
So something like this for ground collisions?
its just this part rb.AddForce(transform.up * jumpForce);
the other lines are other things I tried and doesnt work
i presume a ContactState would remember values
AddRelativeForce was wrong because that converts from local to world space
so transform.up would be...double-transformed into world space, basically
AddForce(transform.up * jumpForce) is wrong, but it's in the right direction
What do you mean?
It should be rb.AddForce(transform.up * jumpForce, ForceMode.Impulse)
it's an instantaneous change in momentum, not a steady force
Correct me if I'm wrong, if the object is turned sideways and tries to jump (sideways), wouldn't that rigidbodies x velocity increase instead of y?
public class ContactData {
public bool wasGrounded;
public Vector3 groundNormal;
}
that kind of thing
I think i already tried that and it didnt work, imma try it again tho
i don't think you need to rush to implement something like this :p
that won't change the direction
Yes. I'm just pointing out that your force mode was wrong for a jump.
This won't fix your problem. It's just something you should fix while you're looking at it.
yeah it still dont work
ForceMode.Impulse means "change the momentum by this much"
The default, ForceMode.Force means "apply this much steady force"
I still dont get why it isnt working, i think its the gravity script the problem but idk
I wonder if messing with the transform's rotation is causing any problems for the rigidbody
That could explain why it's kinda...going up and down
Like this?
maybe
consider setting the rigidbody's rotation directly instead -- rb.rotation = ...
I don't know how it stores momentum internally. If it's in local space, then this would make a fair bit of sense
yeah i tried alrady that
rb.velocity is world-space, but who knows if that's how it the info is actually stored
mm okey, im going to try that and see
Ye
I seem to mostly get an issue with my IDE not being linked to Unity especially when I create a new project. As you can see the Debug.Log has no hover and is normal text so it has no knowledge of Unity it seems. So if anyone especially on a Mac knows more about the right procedures I appreciate your insight.
I'm running on a Mac with Visual Studio Code and Unity 2022.3.4f1 [for silicon]
I'd like to inquire if there are certain steps you need to take with registering your IDE (in this case Visual Studio Code) and/or in each project you create you need to install the Visual Studio Code package - but I'll pause on that question/answer for now
yes I used this to work around using new stuff, I get intimidated for some reason
This is a legacy package that's no longer used.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
Follow the instructions for VS Code.
Thanks Fen!
your External Tools screen should look more like this after removing the old package and installing the Visual Studio Editor package
so i'm trying to make this basic async/await code that just logs something, waits for the player to press space, then logs something else. It logs the first thing, but pressing space doesn't do anything. Did I use async/await wrong?
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public class AsyncStuff : MonoBehaviour
{
// Start is called before the first frame update
public bool onOrOff = false;
void Start()
{
DoTheAsyncStuff();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
onOrOff = true;
}
}
public async void DoTheAsyncStuff()
{
Debug.Log("Started");
await new Task(() =>
{
while (!onOrOff)
{
}
});
Debug.Log("Finished");
}
}
doesnt work š¦
i basically just want a Fixed version of LateUpdate. I don't care about general execution order, i just want something to run after FixedUpdate
that doesn't tell me what you're trying to accomplish
only how you've tried to solve your problem
what are you trying to make your game do?
void Start() {
DoAsyncThing();
}
private async Awaitable DoAsyncThing() {
Debug.Log("Start");
while (true) {
if (Input.GetKeyDown(KeyCode.Space)) break;
await Awaitable.NextFrameAsync();
}
Debug.Log("Finish");
}```
Would that not need to be in Update?
Why would we want to introduce Update here?
How is it gonna get when he puts a key down
That's what cs while (true) { if (Input.GetKeyDown(KeyCode.Space)) break; await Awaitable.NextFrameAsync(); } is for
so let me make sure I understand how await works - basically, the code runs until it reaches the await, which it says "ok, lets take a break and then keep going next frame", and then it keeps going the next frame?
await Awaitable.NextFrameAsync(); says "come back to me next frame"
so yes
Oh right but that would lock him into that function and loop with that script, would a Boolean as a check and having it in update not make more sense?
Depends what he is doing I guess
No it wouldn't lock anything. We have await Awaitable.NextFrameAsync(); in the loop which waits one frame and lets the rest of the engine run
Ok, I've setup a simple cube and I think it's something to do with the player controller right
so say I awaited a function instead of Awaitable.NextFrameAsync(), what would that do?
in the same analogy thing
You can only await a Task or Awaitable. It would wait until that thing is done
ah, good idea !
Thanks @swift crag . Towards the end of the instructions, I had everything completed. Restarted both Unity and VS Code, opened my code but the Debug.Log statement was still a plain cyan color. I could hover over items such as Update() and tell it was referencing some Unity knowledge; however, when I removed the Debug.Log line and began to retype it, then and only then did it change color. Any idea why it was just oblivious? Thanks!
Maybe your player controller is storing your velocity in local space or something
so if I awaited a task, it would not continue onto the next frame until that task is finished, allowing the rest of the async code to keep running, finish, and move onto the next frame?
If it's not auto-completing things like Debug.Log for you, then it's not working right
I'm going to go through the script and see, but it 100% has something to do with that since I'm directly using velocities for the player movement
quit VSCode, hit "Regenerate project files" in the External Tools window, and then double click a script asset to reopen VSCode
nothing to do with frames. It wouldn't continue your code until that task is finished'
the rest of the code in the async function will not run
It runs in order top to bottom
so whats the point of awaiting a task if I can just use a function instead and then call the function? Wouldn't that have the same result?
When I open the script I'm not exactly doing a auto-complete - it's just displaying what's there. and yeah I did do the Regenerate project files as you said and it gave me the plain cyan.
When I retyped it, then it provided proper coloring. I can't say 100%, but I'm pretty sure, that a hover when it was cyan didn't illude to Unity information. This is what it looks like re-typed (normal)
a regular, non async function will freeze Unity until it is complete
If the function is small/fast enough, then that's fine
I thought thats what you said the async with task would do, stop everything until the task is finished, and then continue the code
if it's something you need to do over multiple frames, you need a coroutine or async
it stops the async function that is awaiting it. It doesn't stop the whole game engine
synchronous (normal) functions stop the whole game engine
ah, so everything else continues, but the async function stops
yes
so the async function is in its own little timeline thingy
I suppose you can think of it that way
Async: into the awaitverse
so then in that case, should've my original code worked? Shouldn't the task that I created just simply wait until onOrOff is true and then finish?
I want a smoother landing like in Cluster Truck. How can I implement it in Unity?
never played it
you'd have to describe
The task isn't goiong to do anything
you can't just new up a Task and await it
The task wasn't even Start()ed
also if you DID start that task it would freeze unity because it will run on the main thread
unless you ran it on a background thread
My problem is within these lines, I've tried disabling this function and the player falls normally, now I dont really know what is the problem tho.
{
Vector3 currentVelocity = rb.velocity;
Vector3 targetVelocity = new Vector3(move.x, 0f, move.y);
targetVelocity *= crouching ? crouchSpeed : (sprinting ? sprintSpeed : speed);
targetVelocity = transform.TransformDirection(targetVelocity);
Vector3 velocityChange = (targetVelocity - currentVelocity);
velocityChange = new Vector3(velocityChange.x, 0f, velocityChange.z);
Vector3.ClampMagnitude(velocityChange, maxForce);
rb.AddForce(velocityChange, ForceMode.VelocityChange);
}```
There is a bunch of videos in the internet
It's very hard to describe it
You need to see
it's that game where you jump from semitruck to semitruck
yeah
and the trucks are all in various states of violent motion
Basicly I want the camera to continue going down when the player lands and smoothly go up to the right position
Actually it might have worked if you started the task before awaiting it (because i think it will run on a different thread), but a spinloop like this is very inefficient. It will basically peg one of your CPUs at 100% until you press the key@thorn holly
just put a small lerp / smoothing ping pong type thing.
its only slight VFX I dont see it often , only on high land
oh
Can also experiment with spring joints no? 
from video I saw is just a quick camera trick, idk if rigidbody would be overkill
Mathf.PingPong ?
or like Dotween
Oh wait yeah I forgot about rigidbody lmao nevermind
So i know this is like the xy problem but this was very useful for me to understand async await. Now if I were making a selection process thing where some buttons appear, select one, buttons go out, new ones appear, select one, etc. Would the best way to do this be a coroutine so that all of this stuff can occur over multiple frames? Or how else would I go about this?
https://youtu.be/VesKV9_yDUc?t=573
play at 0.25x speed. It only happens when you land from high jump
Check out over 24 minutes of gameplay from an alpha version of Clustertruck, an absurd first-person action platformer from Landfall Games. Read more at: http://www.polygon.com
Like Polygon on Facebook: https://goo.gl/GmkOs4
Follow Polygon on Twitter: http://goo.gl/cQfqrq
{
float healSpeed = .3f;
isHealing = true;
if (health < maxHealth)
{
health = Mathf.Lerp(health, maxHealth, Time.deltaTime * healSpeed);
...
}```
My lerp slows down at the end
is the issue with T not being between 1 and 0 or is it smth else
merci
coroutines and async/await are solving the same problem. You can use either one. And the thing both of them are doing is actually just creating a lightweight state machine.
For a selection process like you described I feel like it might be better to just make a full fledged state machine.
to the google I go, to figure out what a state machine is
thank you
might be formally called FSM or Finite State Machine too
Currently my IsGrounded() check is being strange, it is only true every once in a while even though I am on the ground.
Without seeing your code all we can say is there's something wrong with your code.
if you're using from CC one then it only works while moving usually
Sorry. Here is how I determine the IsGrounded() and the value of IsGrounded is what I'm printing to console.
well there's your problem
have you read the docs for isGrounded?
https://docs.unity3d.com/ScriptReference/CharacterController-isGrounded.html
It basically checks if your most recent call to Move tried to push the CC into the ground or not
Long story short, most people write their own grounded checks because this one is not good.
yeah def go for a checksphere/box, sphere/box cast or overlap
I'm afraid I don't have the knowledge/experience to cover the missing gap. I've tried several ways to try to make what I'm sure your logic works into my code.
If you're willing to help guide me once again, I've simplied my code into a new project. Let me know if you can assist. Thanks!
I have an example here if you want to check it š @elder osprey https://youtu.be/cEQdjYk51KQ?t=491
it's invalid because...
bool foo = true;
foo.WasPressedThisFrame;
foo is a boolean. it doesn't have a member named that
that's all
I'm pretty sure my error is where I need to put your statement before the part about bools
here's what I have layed out.
Input Controller script:
using UnityEngine;
using UnityEngine.InputSystem;
public class HumanoidLandInput : MonoBehaviour
{
private InputActions _input;
public bool BackpackActionIsPressed { get; private set; } = false;
public bool BackpackActionIsReleased { get; private set; } = false;
private void OnEnable()
{
_input = new InputActions();
_input.HumanoidLand.Enable();
_input.HumanoidLand.BackpackAction.started += SetBackpackAction;
_input.HumanoidLand.BackpackAction.canceled += SetBackpackAction;
}
private void OnDisable()
{
_input.HumanoidLand.BackpackAction.started -= SetBackpackAction;
_input.HumanoidLand.BackpackAction.canceled -= SetBackpackAction;
_input.HumanoidLand.Disable();
}
private void SetBackpackAction(InputAction.CallbackContext context)
{
Debug.Log(context.phase);
BackpackActionIsPressed = context.started;
BackpackActionIsReleased = context.canceled;
}
}
and here's basically the script on the player:
using UnityEngine;
public class Backpack : MonoBehaviour
{
[SerializeField] private HumanoidLandInput _input;
[SerializeField] private GameObject uiTest;
[SerializeField] HumanoidLandInput backpackActionReference;
public bool ToggleBackpack => _input.BackpackActionIsPressed.WasPressedThisFrame();
// Update is called once per frame
void Update()
{
if (_input.BackpackActionIsPressed)
{
Debug.Log("test");
uiTest.gameObject.SetActive(true);
}
else
{
uiTest.gameObject.SetActive(false);
}
}
}
for now ignore the line on the 2nd script that reads:
public bool ToggleBackpack => _input.BackpackActionIsPressed.WasPressedThisFrame();
i know that's wrong
very sorry for the spoon-feeding
BackpackActionIsPressed is a bool. Why are you trying to call WasPressedThisFrame on it?
It may be easier to use events here. It'd look like this.
public class MyInput : MonoBehaviour {
public event System.Action OnBackpackToggle;
void HandleInput(InputAction.CallbackContext context) {
OnBackpackToggle?.Invoke();
}
void OnEnable() {
_input.HumanoidLand.BackpackAction.performed += HandleInput;
}
void OnDisable() {
_input.HumanoidLand.BackpackAction.performed -= HandleInput;
}
}
Anyone can now subscribe to OnBackpackToggle to have a method called when the action is performed.
kind of, but nothing in contact state should depend on the character controller
again, keep in mind that the Update() on the player is enabling and disabling the uiTest gameobject as I'm pushing in the button
Exactly like what you're doing with _input.HumanoidLand.BackpackAction
if I were ro delete your character controller, ContactState should have nothing break
PlayerMovement depends on ContactState, not the other way around
also, conceptually, it wouldn't be very useful if it just told you things that are currently true about the controller, after all
you already know all that stuff
the whole point of having a separate contact state is for the contact state to have all the variables describing contact
at this point I'd just use an InputActionReference to cut out the middleman
let me show a brief example from my game...
using UnityEngine;
using UnityEngine.InputSystem;
public class InGameMenu : MonoBehaviour
{
public InputActionReference menuAction;
void OnEnable()
{
menuAction.action.performed += ToggleMenu;
}
void OnDisable()
{
menuAction.action.performed -= ToggleMenu;
}
void ToggleMenu(InputAction.CallbackContext context)
{
if (MenuController.activeMenuController != null)
MenuController.activeMenuController.Hide();
else
MainMenu.Instance.controller.Show();
}
}
an InputActionReference allows you to reference an InputAction from an input action asset
it does not automatically enable the action, so you'd probably want to keep your existing code in HumanoidLandInput
I find these to be supremely useful -- I just hand out action references as needed
each "thing" you can do includes an input action reference, so I can set which action performs it
then you have multiple bindings for a single input action
not a problem at all
why does it not jump/fly up when i press spacebar?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BirdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public CircleCollider2D mycircleCollider;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myRigidbody.velocity = Vector2.up * 10;
}
}
}
then ig some kind of Dictionary would work
those are completely invisible to me here
@swift crag I'll absorb and try - ty!
I have Mouse + Keyboard and Gamepad control schemes
Dictionary<PlatformEnum, InputActionAsset>
but I don't care about them at all
they're all in one input action asset
I only care about those when I need to update the control hints I'm displaying
if you're just making for PC then yea it'll work great ig
I don't understand what you're talking about. You don't need multiple input action assets.
Step 1 use Debug.Log to make sure your code is actually running as you expect
im not talking about multiple input action assets
one input action asset, you can have multiple control schemes in it
but then what is this...?
yes, I understand that. I have multiple control schemes.
hold on let me open the project and screenshot it
Alright @wintry quarry I think I understand fsm's, so for my selection machine, I could have some states like ButtonGoingIn, ButtonBeingSelected, and ButtonGoingOut, and the I can just use transitions to switch between them, passing in different parameters for what buttons go in and what buttons go out as I go.
I guess control schemes are more for input "parts" instead of platforms? Like one scheme for on foot actions, and another for when driving
different bindings are associated with different control schemes
these are input action maps
So in that specific case, it would be a very linear fsm, because everything just proceeds to the next step.
hi guys i want to create a unity project that simulates human falling (tripping over,falling,slipping...) to simulate and extract data to feed it into an AI in order to help people with special needs or individiuals that have body problems (after accidents)
i want to ask if it is doable using Unity ?
different input action maps can contain different input actions, which can have multiple input bindings
this code isnt running until i click a button on the Ui for some reason, then it just cuts to a differenet frame and idk why
RenderSettings.skybox.SetFloat(Rotation, Time.time * rotationSpeed);
tf is an input scheme then
how do i enable it
@swift crag imagine making a game for NintendoSwitch, where you have multiple usage mode (single joycon, double joycon) etc, and you have just one InputAsset (which is correct) but multiple schemes
@rare basin are you talking about this dropdown box? [All Control Schemes]
a control scheme is a collection of input devices
yes
of course. Plenty of people have done this. Look into "active ragdoll"
How do you enable what?
okay, and?
debug.log where can i find it
Anything is possible with enough knowledge š
and you don't have input actions that are in scheme A in scheme B
that's why I was talking about the Dictionary
My onTriggerEnter method works, but for some reason my event doesn't invoke like it should once the OnTriggerEnter method is called
control schemes do not have actions. are you talking about different action maps?
thanks boss
eh.. action maps have actions
if some actions can't be performed by some devices, then that sounds like a design problem. input actions are supposed to be high-level ideas
alrigfht thanks
i fixed it
action map in scheme A doesnt have actions that are in scheme's B action mpa
hi its my second attemp in unity, does anyone know how to make player visible in front of some object and invisible behind it? (2D)
@wintry quarry do you know similar projects to ragdoll?
it was just simple i didnt put my rigidbody in the script
let's talk about this in #š±ļøāinput-system if you want to continue; we're cluttering the chat
define what "behind " is
you could either shift Z pos or the Order In Layer
well some actions can't be perfomred on some edge cases on nintendo switch, depending on the joycons connection
wdym by "projects"? active ragdoll is a concept, not a project.
https://pastebin.com/fPnfBBM9
Does anyone know how I can make the Rigidbody Rotate based on input and go forward in that direction using this code?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
sorry i'm not very familiar with Unity, i'm just trying to have it run just to extract data (for tripping,slipping....)
you could either split that in 2 peices or if you have the pivot at the feet for both you can do some math to determine which one should be infront
like if your Y pos is larger than the tomb Y pos then show Order in layer infront
Hello!
I managed to instantiate the objects how i wanted, but i think i require some help in figuring out how i need to link the hinge joints to one another. I want to link them counter-clockwise starting from the highlighted piece, but with what i managed to do until now, it doesn't really work and i don't know why. i am trying to achieve a closed-loop chain of hinges.
this is the code i'm using for it: https://paste.myst.rs/cooapqxl
a powerful website for storing and sharing text and code snippets. completely free and open source.
haven' worked on 2D too much, just tiles for that so I have 2 tilemaps
I want to make a custom physics system. I want my PhysManager.PhysUpdate() method to execute after all scripts that mutate my PhysObject class instances are finished (in FixedUpdate).
Ah, mimicking what Unity is doing: FixedUpdate, then the physics step
well, hmm, if you don't mind waiting until after Unity's own physics is done, you could use a coroutine with yield return new WaitForFixedUpdate();
You're missing some curly braces for that if statement?
Hey guys, I'm trying to figure out how to handle procedral generation for my 2D rogue like game. It takes place in a city and I want each pre-made prefab to be placed in randomly, but still ahve the streets on the other prefab connect seamlessly. any ideas where i can start with this?
hey, im having a problem with clamping my velocity unsing the Vector2.ClampMagnitude. My problem here is that it also, I think, clamps my verticle velocty as well instead of just the horizontal velocity. What sould I do? Here is my code:
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxRunningSpeed);
}```
consider splitting it into two floats that you clamp independently
then just stick them back together
how do I do that?
do you mean in the if statement or when I am clamping the velocity?
Vector2 velocity = rb.velocity;
velocity.x = Mathf.Clamp(velocity.x, -maxRunningSpeed, maxRunningSpeed);
rb.velocity = velocity;```
or in Unity 2023+
rb.velocityX = Mathf.Clamp(rb.velocityX, -maxRunningSpeed, maxRunningSpeed);```
ohhh ok, btw what is the diffrence between Mathf and Math?
Mathf is for floats
Math does most things with doubles
Mathf was created by Unity.
Math was created by Microsoft
Mathf basically recreates most things in Math but with float params and return values
ah alr, thanks!
Ah that was a mistake. Even if I include the curly braces tho, the event still doesn't invoke.
is log printing ?
Does anyone know what could be causing this error on WebGL builds:
RuntimeError: memory access out of bounds
However, running the build on a local server works fine. What's even weirder, it worked once on itch.io, but after loading it subsequent times I get this error
I tried every compression format in the player settings, as well as every "enable exceptions" option
this looks like what i was looking for, thanks š
Someone knows why this marks an error?
Hold your mouse over it
Tldr it's incomplete
wdym
It needs at least one yield statement to be valid
for example yield break; or yield return null;
similar to how this is in error because there's no return statement:
int Example() {
}```
Can I have an eventhandler for each enemy or is it better to not use events for many objects in a scene?
Oh, i never knew that
Is there any way to make an IEnumerator go in loop
same as you do any other loop
Oh am dumb
i place it at the end right?
IEnumerator Stuff()
{
while(condition)
{
// Does stuff
yield return null;
}
}
you should use the C# events
and you can have many events, doesn't matter
I want to create characters for my game, my idea for this is to make a "character" gameObject with "IdSelector" script attached to it. In IdSelector you will choose 1 id from the whole list, and it should automatically choose correct sprite, scripts and stats. How do i do that? I need to know how can i connect public float ID to the list in character selector.
Im using C# events
Ok great thanks
then there is no problem š
yea the log is printing
where do you subscribe to event
Just pass the ID from the player to the character selector and return all data needed.
How do i pass it and return the data? Im very new.
By going through a C# course, if the thing you're asking about are functions and how to use them
These are the two classes that I subscribe to the event
I cant find any polish c# courses, and im too young to afford a paid one. Can you just tell me?
put debug.log / breakpoints there to see if its hitting.
Also cleanup your events with -= in OnDestroy
But generally you figure out how to get the reference to the character selector from within the player in a reasonable way, you call a method from the selector, let's say selector.GetData(myID); where the return value is some kind of struct/class containing the data
that is a terrible idea to use Find methods
in general
and in your case especially
I need help with a script, i now how to make objects disapear when i run over them with the trigger function, but how can I create a script that knows that when i make 4 of this items disappears, it changes the scene to the victory scene. And i need that when u pass through the object a sound and a text appears. (But the text disapears like after 5 seconds)
Hey guys i was wondering if someone could help me witha rounding problem so im trying to make a flying sword for my game in unity2D and everything is working excpet when the word is flying i want it to come back it reaches its targetpoint before it reaches its maximum flight time before coming back automatically so i have this code. i know the issue is in the bottom if staement where we set the evctor directly to the target pos and since the target posis a float ik when we are usign move towards the sword will never make it exactly to the target and i know it will always be .1 off from the target so what can i do to round or check its close to the target?
void Update()
{
TimeBtwnThrows -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (TimeBtwnThrows <= 0 && transform.parent != null)
{
TargetPoint = Camera.main.ScreenToWorldPoint((Vector2)Input.mousePosition);
transform.parent = null;
IsFlying = true;
}
}
if(IsFlying)
{
if(FlyTime < MaxFlyTime)
{
transform.position = Vector3.MoveTowards(transform.position, TargetPoint, FlySpeed * Time.deltaTime);
FlyTime += Time.deltaTime;
}
else
{
if (FlyTime >= MaxFlyTime || transform.position == (Vector3)TargetPoint)
{
transform.position = Vector3.MoveTowards(transform.position, ObjHolder.position, FlySpeed * Time.deltaTime);
}
}
}
}```
Heres video
very simple keep track of each item destroyed and if they == a number then game won
There should be a few free polish ones for sure if you look hard enough - and more than enough english courses. When it comes to programming you generally kinda need to know english because... most of the good materials are in english, unless you find a translation.
does this generate between -0.5 and 0.5? i know u gotta have an extra +1 or something
Whats the line of code for that
I edited the message
I need help with a script, i now how to make objects disapear when i run over them with the trigger function, but how can I create a script that knows that when i make 4 of this items disappears, it changes the scene to the victory scene. And i need that when u pass through the object a sound and a text appears. (But the text disapears like after 5 seconds)
Thats the complete one
i dont get whats the question sorry
Like a mario coin, when i get it, a sound appears and a text too, and after getting four, i change scene to "Victory" Scene @rich adder
https://learn.microsoft.com/pl-pl/training/paths/get-started-c-sharp-part-1/
Actually, there's a Microsoft c# course available in polish. I don't know how good it is, but I suppose it can't be too horrible if it's coming from Microsoft.
learn english first then
yes, but whats the problem with your script. Whats it doing now vs what it supposed to do
I know english a bit, but when i read docs they always use some very hard words that i dont understand
can't be good at programming without atleast basic english
translators and google exists
if u not going to help then dont speak up maybe!!
Thats the problem, i dunno how to make that code, is difficult for me, im new
i am helping
you are not listening
start with the basics
how do we check if another number equals another
etc
there are c# courses pinned in this channel
yeah i now, but im nervous because its the last thing i need to make for my game
that is why google translate exists
xd
Then start with something a bit easier than the docs, these may be a bit too confusing for absolute beginners. Heard that w3schools offers a nice free C# course. Also, same as with programming, research if you do not understand some words - translators and google as Xaxup mentioned.
wdym last thing? How did you do the previous stuff if you can't simply do a == check
alright, i will try
thank you
no like, thats the only thing i need to finish the game im making, its my first game ever
3d game
how did you make that game then, when you completely don't understand the very c# basics
im trying to make a player get stopped by a wall in a practice game im making but even after using tilemap colldiers and composite colliders nothing seems to work
could someone help
with some help and tutorials
Either way, try to go though all of it and make sure you understand everything presented there more or less. Basics are important and you're gonna need them at every step when programming in Unity, so there are no shortcuts.
i know a bit of it but not that much
There's no one line of code but a series of events you need to do:
Create a script to track the score
Update score text to a new value
Etc.
You'll need to look at some tutorials first since you don't have any pricked or errors we can help with. There are a lot of resources for Mario clones . . .
dont you just need to give a collider component to the wall and the player?
ok ok, ill try
i have but it still doesnt work
player has the box collider and the wall has the tilemap collider
then you learned nothing?
you just copied
not a good way to make game
ik ik
chat-gpt style like
start with breaking down your problem into smaller ones
This generates a number between -0.5 and 1.5 . . .
do you know how to keep tracking of items destroyed ? @signal bronze
adding an integer ?
i know basics, but from experience i know that courses dont help me that much. I have tried few ones, but i always forget what they say. I know that i can learn only from tutorials. Its way more difficult way but i can remember when i do so
i think i do yeah
so you know, or you think you know?
Hi, I have a problem with boxcolliders, so basically I have a raycast based suspension, and the car center of mass isnt at the center, so when the car isnt moving, it slides back a bit, is it possible to automatically set it to the center?
You only gotta have an "extra" +1 when it comes to integers (depending on the method implementation)
like this?
well, the thing i dont know how to do is play a sound after u get one and to change the scene after i get four
we're doing circles
so ? thats what we do , one problem at a time
ezz
thanks my g, apreciate it
you can't understand the provided help
You already solved the counting part, now move onto the next goal
Hey guys i was wondering if someone could help me witha rounding problem so im trying to make a flying sword for my game in unity2D and everything is working excpet when the word is flying i want it to come back it reaches its targetpoint before it reaches its maximum flight time before coming back automatically so i have this code. i know the issue is in the bottom if staement where we set the evctor directly to the target pos and since the target posis a float ik when we are usign move towards the sword will never make it exactly to the target and i know it will always be .1 off from the target so what can i do to round or check its close to the target?
void Update()
{
TimeBtwnThrows -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (TimeBtwnThrows <= 0 && transform.parent != null)
{
TargetPoint = Camera.main.ScreenToWorldPoint((Vector2)Input.mousePosition);
transform.parent = null;
IsFlying = true;
}
}
if(IsFlying)
{
if(FlyTime < MaxFlyTime)
{
transform.position = Vector3.MoveTowards(transform.position, TargetPoint, FlySpeed * Time.deltaTime);
FlyTime += Time.deltaTime;
}
else
{
if (FlyTime >= MaxFlyTime || transform.position == (Vector3)TargetPoint)
{
transform.position = Vector3.MoveTowards(transform.position, ObjHolder.position, FlySpeed * Time.deltaTime);
}
}
}
}```
Heres video
how to do is play a sound after u get one
turns into
"how to play sound in unity"
for example
so now we are teaching people how to use google, right š
well not many people know how to, this is #š»ācode-beginner so its acceptable
Always try to put the things you learn into practice. It's easier to remember it then. Don't just read through it all at once - if you see something new then read till the topic about it ends and try it out by yourself, mess around with it a little - or even try and search for courses with some tasks to complete. Oh and I'm also Polish, so powodzenia.
If you did your game by using specific tutorials, you can basically ask ChatGPT āhow to play a sound in unityā
Thank you, I will
we should have #google-beginner channel
bad advice
dont
Yea I just realized it was
please
pre-K Coding
What's going on here
It is bad, but he made his game with no c# knowledge
copying tutorials , which is working code at least...mostly
The only concern would be when it doesn't work - no one will debug the AI's mistake. You'd better be able to catch it yourself.
why are so many people bringing up the spam machine today?
gpt is nonsense spam
doesn't mean he should copy/paste now, but from chat-gpt instead of yt tutorials
i feel like i'm seeing it every half hour
Spam? haha
people who get banned and come to troll š
LLMs are machines engineered to produce enormous amounts of plausible looking spam
and they're giving me a damn headache
Its easy to say, but not that easy to follow. I were trying to learn unity from courses for 2 years, but did 0 progress. Its my 3rd year using unity, but now im learning with tutorials and i do much, much better
wont happen
At least it works⦠sometimes, and basic things
Btw, can i DM u? Its way easier to ask for help in ur native language.
Im against AI powered chips personally
if you are learning for 2 years and there is 0 progress, then I'd say Unity is not for you then lol
how is that possible
anyway but lets keep this channel Unity beginner coding questions,
this is like the 3rd time today we talking AI and its redudant lol
dont worry, ill do it by myself, looks like people is anoyed about other people asking for help in a discord chat that was made for that, have a greate day @rich adder ā¤ļø
As long as I'm free and I can answer within a reasonable time, then sure
Told u, that courses are not for me. Everything i learn falls out of my head immediately, but i like coding and like making games, thats why im not giving up. As i told u, if ur not going to help, then dont say anything
Oki
If you didn't learn after two years, you're doing smth wrong, and the discipline is not there . . .
No worries, people want to help but, as long as you show you are willing to try yourself its no problem.
If you go into "pleezz write cude for me" then yeah people will get turned away
You should always try doing it by yourself, if you have a problem and really canāt figure it out, I think that itās the time to ask here
Ik Ik, but ill try to do it for myself witout any help, thanks anyway
thats because you dont practice enough what you just learned
so you will forget it quick
chill out big man, just interesting that you can learn something for 2 years and dont learn anything lol, anyway cut the spam
new information needs repetition for brain to retain
Hello, how to change this UI image width based on a variable?
float currentGreed = 0f;
float maxGreed = 100f;
use fill image
and change the fillAmount
the property on it that says fill amount
I am chilled out, but you dont help, u just say that i should give up or some other dumb "tips"
if its a slider then its the theSlider.value
i never said you should give up?
You said unity is not for me tho
We help answers questions with issues and/or errors in your code. That implies you have code available to look at and debug. If you haven't started or know how to do a specific topic, that is when you look online for tutorials, forums, blogposts, or docs
We don't walk people through a step-by-step guide because those are already online . . .
and docs**
and chat gpt kappa
oh pls dont start
Depends what he means by "learning". Honestly, my first year with Unity when I was younger, was just me blindly trying random tutorials and making random things. Technically I did something, but didn't learn much from that, lol. Only in the following years I began to actually learn properly. And he said he's young, so chill, young people don't think and learn in the same way adults do. He'll get there eventually if he commits to it.
sure, never said he won't
My concept of learning is making a game, and then when I run into an issue or something I donāt know how to do, I get some help here, then do a bunch of research on the concepts that I learn
It works pretty well, I feel Iāve made decent progress
I think that is the problem when you are trying to learn Unity. You type in YouTube tutorials for āHow to make character controllerā and you copy out the entire code. But what you should do is understand how transforms work in Unity, and have much more abilities and be able to do way more things
yeah but you can't know about something until you start using it
thats when you should question what the component is and what you can do with it
why does this keep randomly popping up?
Unity editor issue. You can ignore . . .
thank god
If everything you learn "falls out of your head immediately", then I suspect you aren't approaching learning correctly
Probably, yes
your layout is taking a quick shit
if it bothers you much and you aren't currently using any windows that use the shader graph, then close them (like the Animator) and it will stop for a while
Agreed. That's not learning . . .
ohh ok
if you just watch a course and think "ok I learned the course", you've probably missed most of the information
agreed, there is literally NO WAY you learn something for 2 years and you don't even know the very basics
You need to see how something works, then do it yourself -- first in a very paint-by-numbers way, then with more freedom
Unity Learn tutorials encourage that kind of thing
imagine going to school for 2 years in maths class and you still dont know how to substract/add numbers together
can anyone see why the walls wouldnt stop the player from moving, im using rigidbody velocity
repetition of what you just learned is good way to engrain it in mind
ive been trying to solve it for atleast an hour now
trigger colliders are not solid colliders
even when i turn is trigger off for both player and wall it doesnt change anything
i still walk through the walls
are you moving through modyfing transform.position?
collision matrix configured properly?
When I started tutorials, I typed all the code and redid the tutorial solo to ensure I knew how. You should strive to understand each line or code before you move on
The problem is, it's a slow process, and people need instant gratification or results to feel like they are doing smth . . .
how do i know specifically what it means?... "uknown" and "this" are not giving me that many clues
probably that because i have no clue about what a collision matrix is
this means that Unity can no longer find the script asset
all it has is a numeric ID
but it can't find anything with that ID
how do you change the collision matrix

ye that game was paused this is what happened when i unpaused š
Did you recently change the name of a script? It means it cannot find the MonoBehaviour because it is missing . . .
thats the thing, i didnt change any names
did you change anything on script and save while running game?
Did you change/edit the script while the game was paused?
Unity's "hot reloading" can produce weird results
possible.. had to change the script a few times, i could have not paid attention and did this
where do i go from here
clear them from console and move on?
As long as it doesn't appear when you start the game again, you are fine. Unexpected results from reloading (as Fen pointed out) . . .
you asked this earlier and got both times a yes answer
anything is Doable in unity with enough knowledge and patience
feed it into an AI
is very broad too, feed wat data?
alr ty
I don't see why not, you just need the data which isn't Unity specific . . .
i got the AI part (i just need data and a projectt to simulate), can i reach out to you by DMs to possibly hire you?
from the things i can see the matrix is only on physics 3d
I swamped with projects right now but you are looking for a coder you can try posting on forums !collab
We do not accept job or collab posts on discord.
Please use the forums:
⢠Commercial Job Seeking
⢠Commercial Job Offering
⢠Non Commercial Collaboration
im making my game in 2d
Physics2D exists you know
not true
yes there is
Are you seriously suggesting you want to train an AI on physics simulation data and use that as input to humans?
there certainly is
The matrix is everywhere . . .
nvm im just blind i didnt see the tab
please send the link
sorry
I sent it #š»ācode-beginner message
They did in their response . . .
Click on them . . .
not exactly i will have my university professor with the help of a few doctors evaluate and imrpove it that's why i need someone that knows Unity
aint never gonna work
why? is it because there's not enough randomness factors?
no because there is just not enough data, you need a serious MoCap setup at the least for that kind of data fidelity
did you really want to simulate injured people movement by ragdoll in unity?
i think that i didn't explain it more clearly its way easier
your model will be crap, believe me
okay i got scared lol š
we have to do it and improve it even if it takes 10 years because its better than experimenting on yourself or collecting data from real subjects
not gonna happen. have you ever trained even a simple ML model?
yes
why?
then you should know how much accurate data it needs to train. There is no way Unity can provide you with that for your purposes
can i hire you to help on it?
no lol
why?
those big-scoped projects usually have insanely big budget
and entire team working on it
budget 5$
@rich adder this is what i got, ive changed some things but nothing happens when i get 4, so yeah, ill need help at the end
Do you have a budget of at least 20 million USD?
20 million rupees?
no USD
you are not calling CambiarEscena anywhere
dream on then get real
also wouldnt that cause stack overflow?
you need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
when do you. call CambiarEscena?
pretty sure that will cause stackoverflow tho anyway?
Oh didnt even see that
I don't even know what this magical project is because you keep deleting posts but from context you are likely in way over your head
dont think so
it will switch scene and hit if statement there at most with 0
probably just cause infinite recursion and lock up the thread, i don't think the stack would actually grow there
scene wouldn't load because that happens on next frame
also coding in english will make more sense, especially when you want to share the code/ask for help in english server
btw you should make a method on Inventario
like DestroyedObject() { Cantidad++; If(Cantidad == 4){ //ChangeScene } }
then do == inside that method, instead of manually setting the number variable for counting
Is there any difference between vector3.distance and vector3.magnitude?
Well, one of them is a distance, and one of them is the magnitude
so yes
They have nothing to do with each other
Isn't distance a magnitude?
no
Vector3.Distance(a, b) is the same as (b - a).magnitude though
no
magnitude is length of the vector
distance is well... distance between a and b
One is a function to get the distance between two points. The other gives you the length of an existing Vector.
oh hey, that's actually pretty much exactly what the docs say
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
Vector3.Distance(a,b) is the same as (a-b).magnitude
imagine that
I still don't see how the distance from A to B is different than the length of the path between A and B
They're the same value, they're different concepts.
If you create a vector between two points, the magnitude of that vector will be the same value as the distance between them.
Hey, anyone know how to instantiate an prefab object and set it as a child object (of whatever object the script is in)?
thank youuu
hello fellas. beginner here. I run to this weird issue. i made a simple jump like in a code below. Issue is that if i press jump fast enough it double jumps! why is that?
`private void PlayerJump()
{
if (Input.GetButtonDown(JUMP_ANIMATION) && isGrounded)
{
isGrounded = false;
animator.SetTrigger("TakeOff");
playerBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}`
you can indeed do that all in one step. consult https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Oh sick, thanks
your grounded is probably wrong
perhaps isGrounded gets reset immediately
I don't know how you're deciding if you're grounded.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I would suggest logging when you set isGrounded to true
that'll show you exactly when it happens
also log when you jump so you can see the ordering
very unreliable way to check grounded
what's more reliable?
omg it worked, tysm
OverlapCircle, checkBox/Circle, boxcast etc
are those methods? sorry new to gamedev š
thank you sir/mam
quick example
private bool IsGrounded()
{
Collider2D groundedCol = Physics2D.OverlapBox(groundedCheckCenter.position, groundedBox.size, 0, groundedLayers);
return groundedCol != null;
}```
note that this could, itself, let you jump many times if you mash quickly
until you get far enough off the ground, this will say that you're grounded
this let you jump to the moon in Doom Eternal
Is there a way to prevent rigidbodies from irregular jumping? I've managed to do it directly tweaking the velocities instead of adding forces but I can't manage to make it local to the player transform so it doesnt really work for me. This is what I have right now
I don't know what "irregular jumping" means
What am I missing here to create movement?
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerScript : MonoBehaviour
{
//this field with contain the actions wrapper instance
PlayerControls actions;
void Awake()
{
// instantiate the actions wrapper class
actions = new PlayerControls();
}
// Update is called once per frame
void Update()
{
// the update loop polls the "move" action value each frame
Vector2 moveVector = actions.Player.Move.ReadValue<Vector2>();
}
void OnEnable()
{
actions.Player.Enable();
}
void OnDisable()
{
actions.Player.Disable();
}
}
well, you don't actually do anything with moveVector...
actually moving?
you compute it and then throw it out
lol okay, i had movement going for a while and didnt understand what I copied, so Im going thru Unity documentation to learn exactly how its done
This is what I mean, when I spam the spacebar it doesnt always jump the same amount
ok ill try
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
now i have this, but it doesnt work @rich adder
because you are not calling DestroyObject() anywhere
also as already menitoned
this will cause your Unity to freeze
infinite calling
and how can i make it to be finite
it loads scene called Victoria then triggers a function that is calling a scene called Victoria then triggers a function that is calling a scene called Victoriathen triggers a function that is calling a scene called Victoria
infnite amount of times
that function is an infinite loop, but good thing is you also never call that function from the outside, so it does absolutely nothing either
Yes, though you have to question why you've made a function at all if it's only one line long and it's local
Also, because you've put it inside another function you cannot use access modifiers (ie. public)
you lack basic c# knowledge
how can i make that when i got the 4 items it changes scenes?
if(got 4 items)
{
ChangeScene();
}
like, what should i change here
call the function you made
and you just made a local function
Just have the LoadScene line by itself and remove EscenaVictoria completely
like this i supose
yes finally
now call that function you made
also are you increasing Cantidad whatever it is anywhere?
DestroyObject is never being called too
perhaps you wanted to use OnDestroy unity method?
i do not understan what being called is, it does not mean the same in spanish and i dont get it at all
srry for my low english lvl
the method is not invoked
https://learn.microsoft.com/en-us/dotnet/csharp/methods#method-invocation
set the language on this page to your native language
is this correct? I dont think so
i have no idea what your intention is with this code so i have no idea if that is going to do what you want
that will cause to load the scene multiple times
it shouldn't. it will call LoadScene then the next frame will load the scene
ow didn't know that
i thought its loading scenes asynchronusly
so if the scene is kinda big it would take some time
nothing like i wrote either
nowhere did I put Update() there xD
try it.
and did you remove the ones from the other script ?
i think im having a stroke between understanding the english + trying to do this
what ones? dont remember
where you are doing +1 from other script
you should only be calling this method OnTrigger
no
i copied a youtube tutorial for a resolution dropdown which should display resolutions only with the refresh rate the monitor is set at. but it doesnt work for some reason
nested function
also my eyes are bleeding
"it doesn't work for some reason" idk maybe look at the Red Underline Error
yeah it says its not valid for this item but i dont know why and how
you cannot have an accessor like public when you declare a function inside a function as it only lives in that scope
it changes the scene, but not after getting the 4 items, it changes it instantly after runing the game
I'm sure you didn't mean to nest that inside of Start() though
what do I need to change now
did you remove Update()
that is called every frame, why did you put it there..
i really admire you
helping him since 2 hours š
You created a local (nested) function inside of another unintentionally . . .
i forgor 
I've taught my ex wife how to drive, it could be worse
lmao
Im srry, language barrier + im dumb asf
My family reminds that to all the time
xd
Ik im dumb, but now i need to call the function and it should work?
first needs to be public for you to call from another script, replace the ones where you did inventario.Cantidad ++ in that other script to inventario.DestroyObject() although I suggested Destroyed makes more sense but I understand language barrier š
here?
for me its a name, ik what destroyed means but idc
It really seems like you should follow some tutorials before doing all this on your own
ik srry for disturbing
it's kinda pointelss
we've been telling him to do that
since 2 hours now
im losing hope š
unless someone writes the code for him
sorry
they just need the basics but they kinda getting it, at least they know comm between two scripts
sorta
by the time you are here asking for help
but yeah you need the C# basics
dont have time, im 18 im in "Bachiller", in spain is like the last grade before univesity, i only have time on weekends and with luck, this next week i have 6 exams
ohh thats not what we want to here then
I would love to spend 10 hours a day in this but its impossible to me
you literally wasted 2 hours in the discord asking for help
you could spent that 2 hours for learning
no?
"I dont have time" is not an excuse for not learning
Im doing this shite ontop of 2 fulltime jobs mate
i wanna learn but i need to sleep too
it comes off lazy if you say I have no time
@signal bronze
I have a very bad organization
its not that hard
not a great student, its hard for me
takes an 1 hour a day even it makes a huge difference
ill try
don't look for excuses
constantly
look for solutions
ik
ofc if you're not passionate enough about something you wont be eager to learn anyway
dont know what eager means
like excited
ah okay
ill try to tak 1 hour every day to learn C#
Idk if ill be able to but ill try
Im srry for disturbing, have a great day and thanks for the help
which method of movement is best for a realistic environment, kind of like gta style of walking around?
can i use a character controller with a player input action thing?
sorry im not too good at this yet
Of course. Input handling and how you move the character are totally separate things
so does movement work without the Input manager thing if i just use the character controller? im confused
Why wont this work?
Script 1:
public int health;
Script 2:
public TextMeshProUGUI HPCOUNT;
HPCOUNT.text = Toy.health.ToString();
Two scripts are connected already because first i a scriptable object and the second has a reference to it at the start of my code
i just read up alot on unity about the new input system, and i wanna do it with a player input component and input action asset
How are you referencing Toy?
but then i coded pretty much the same thing from unity, but of course it doesnt include movement
Do you have an error? How do you reference the SO? Or is the text just not updating?
Oh. Nvm, thank you. I missclicked and changed the class
what the hell?
don't worry, we are all here to learn
you shouldn't have health in scriptable object (unless its maxHealth)
changing data in scriptable objects during runtime is not a good idea
i know, still srry for all of u trying to help me, gn
unless you know what you are doing
Thank you, ill change it to maxHealth
keep your health in HealthSystem class or something
only keep data that doesnt change in scriptable objects
or initial values
is there a way to bake navigation path for the ai on this mesh?
i don't know what to do
Look into nav meshes and pathfinding. Lots of ways to tackle it.
that's what im trying to do but when i click the "bake" button it does nothing @solemn summit
Your SO should have default/base values that your classes copy or pull from . . .
for (int i = 0; i < data.In_office.Length; i++)
{
if (data.In_office[i] == false)
{
scary.Stop();
break;
}
}
does anybody know how to fix this? even when one of the arrays are true, it will stay stop
It would only not say Stop if the first entry in the array was true. It works through them all in order
oh, how do i make it where it will check everything though?
Like you want to check through all data.In_offices and if ONE of them is false do scary.Stop()?
im trying to make it where it checks if all the arrays are false
and if one is not, it will not stop
You want to check all of them regardless if any are false?
yes
Instead, check if any are true. If any are true, then not all of them are false
Oh, just check if any are true and break . . .
You dont need an else statement. That else will still be checking if any one element is false
Hi, just wanna tell u that i actually made it work, thanks for the help bro, fr thanks @rich adder ā¤ļø
but im trying to make the audio stop if all of them are false
Yes, an else statement is gonna be the same issue you had before. Do you know what else does?
yes it will do something different when the opposite thing happens
Else is for doing logic when the above conditions are not met. If you check for true, and then add an else statement you are just checking for false.
False in 1 element
oh'
anybody can recommend an existing ragdoll project for simulating human movement?
Simulating human movement like for a game ragdolling or for an actual real life simulation?
No problem!
glad to hear is working:)
both anything available since i haven't decided yet
what do you even mean by simulating human movement?
ragdolls on their own dont simulate any kind of "realistic" movement, just constraints on joints
Like goofy active ragdoll? Ragdolling when dead/hit? Gotta have some specifics
i guess ragdolling then
no a bit more realistic
To what end, though? What' the goal?