#๐ปโcode-beginner
1 messages ยท Page 217 of 1
Please move on from the argument and just ask the full question
it doesnt matter anymore
They are looking for coders
I linked collab links for them, and it made them upset i guess.
Was just trying to help ๐คทโโ๏ธ
Missed that part, great
I'm a little confused, because I don't believe you will get a normal at 45deg unless there's a mesh collider with a chamfer.
I'm also unsure what this code would do in Update, surely if it worked the cube would rotate at a million km/h because it would repeat the logic every frame?
does your raycast always hit object?
Still checking if tag is null
Still just checking the tag and not the collider or hit
And randomly passing 512 as a layermask?
what might be a simple way to make the Capsule face towards the corner (by script), if it can't use a normal off the corner?
i agree i need to move it out of update
I want to know what is the index of a gameobject is through a script. Specifically i want to put a GetIndex process in the script where the gameobject i want to know its index is placed. How do i do this?
You probably need to go back and describe what you're trying to do, why is there a capsule that you're trying to rotate explicitly to the corner of a specific cube?
Like, i instantiate(from a different script) a bunch of gameobjects and i want each of them to be assinged a number based on their index.
Have a manager (perhaps a singleton) that provides an index that you increase when an object is assigned one
Trying to make Climbing logic. Playercapsule is currently able to latch onto and climb along the edges of a Cube, but gets stumped when it meets a corner, because it just wants to keep facing forward instead of starting to rotate around the corner
(Playercapsule moves by detecting points along the edges via raycasts and moving to closest one in direction of movement)
So basically an int that starts at 0 and increases per instantiate?
how can i check?
put it inside if statement like SpawnCampGames said earlier
so remove .tag correct?
the first one yes
but just wrap the whole Raycast in if() but honestly still think you should use 3D colliders for a 2.5D game unless your player never moves around 3D world
2D colliders will be awkward
wait
more like this
so delete that raycast line and replace with that
if(raycast..
- if hit
ok
you can use ur raycast you have now
I would probably perform a CapsuleCast, that way the normal is actually based on the interaction of the capsule and the corner.
Practically, casting towards the cube would pick one of the two faces. It's only when something interacts with the corner will the normal actually be at an angle to it
ohh with 2d u cant.. as long as it 3d ya
If you debugged the normal you have now I imagine it would be perpendicular to one of the two corner's faces, and that's why your capsule isn't rotating
Yes. Whatever you have to written at the end of the dot chain is the thing you are checking. You want to check the collider, so nothing should come after it except the !=
turns out you can
u cant shove a declaration in there
oh cool
vertx has mentioned there is a implicit cast to bool for null check for it
neat.. i didnt know that.. but like someone said earlier.. if its 2.5D its probablybest to use 3d raycasts
Yes that seems to be what is happening. Thanks for the advice, I'll try that!
but not 100 on that
agreed, unless its a fixed camera scenario 2D colliders will be diffcult even with sprites
i use sprites but big primative colliders around them
chunky colliders like this.. and use 3d raycasts
thicc boy
its working well so far
i suggest that other guy do something similar.. instead of the 2d fiasco.. but maybe it fits his needs idk
navmesh agents with sprites 
๐ lol
what makes you think you declare something inside an if statement ? 
instead of guessing maybe you should follow a basic unity course in !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
ty
no.. declare the variable outside no iff needed.. and then ur physics2d.raycasy line. becomes an if statement below it
RaycastHit2D hit;
if (Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, 512))
{```
then.. in if the raycast hits something u can check thie hit
layer 512 they wont get very far
lol idk what that is..
its to the Clickable Layer
but also i noticed his hit isn't in the raycast..
under my target
use layermasks
how did you come up with 512 ?
Debuglog and it was showing 512
Can't do that, physics2d doesn't use an out param for the hit the method just returns the hit
ya, im getting mixed signals.. i gotta check myself.. b/c i came back to the issue and someone said there was one that returns the bool..
i followed this one guide but
so thats true.. and it doesn't have the hit.. u have to do that extra?
RaycastHit2D has an implicit cast to bool
ohh, okay imma look thru the docs here in a sec..
512 should be layer 10
1<<9
not a practical way to set layers, learn the LayerMask type
magic numbers
i wouldnt have thought of that
Right, 9.
Did they debug GetMask or something? Such a bizarre way to do it
In this tutorial series you will learn how to create an RPG game in UNITY. The scripting language used in this series is C#.
You can get the project files by following this link(This includes all assets like commented C# scripts and sprites, sounds etc.):
https://www.inscopestudios.com/rpg
I will explain everything I'm doing in details so that...
6:15 is where that 512
lol
bad tutorial
I hate that
ill have to watch watch nav sent for beginners
als you copied wrong
yup i thought that too.. made a full circle.. his code was pretty much fine at first..
just need to check for the collider before doing tag comparisons
yes the Learn tutorials are better than this tbh
ty for the help. everyone lol def gonna start watching those
if i use Random.Range which will pseudorandom pick a number from 0 to 8, should i make the maxvalue 8 or 9? Since im seeing a lot of examples where the max value isnt chosen. Just want to confirm this
minvalue would be 0
and i will be using System.Random
int is max exclusive
So the max wont be chosen? Im not too familiar with those terms
Oh the System not unity
whats the difference between them?
I think its still max exclusive
thats what i noticed, both docs on the system and unityengine are the same
they have more or less different methods
Unity one also includes things like color or rotation
etc
but max exclusive means that the value will be excluded from the possible int it can choose?
yea
ic
so if you want max 10 you put 11
so for this, ill put 9 as the max value then
yea
For the first two or three. Then only if you want to do VR and AR
Of course haha
I am making a game that will have many different GameObjects with different values. Just like games with many characters I want to make a system for stats that all will use. Such as having variables for weak, average, strong, and very strong when applying values for Character Stats. I want to know if there is a way to make a list of variables with custom names that will be able to be set in for Floats in the inspector
Instead of the numbers, I would like a drop down list to appear that I can pick from. The item from the list I choose from will be a float variable.
how do i wright the () other kind of these
Not sure what you're asking
() {} [] <>
Take your pick
{} these
Curly braces are what I call them (and commonly see them called)
how do i write them on my keybord ?
Mine are next to the backspace button, and one row down
Just gotta... look for them ๐คทโโ๏ธ
thanks
Is it possible to make a drop down list for Serialized floats in the inspector?
using UnityEngine;
using UnityEngine.SceneManagement;
public class scenechange : MonoBehaviour
{
public float launchForce = 10f;
public float destructionDelay = 2f;
private void OnCollisionEnter(Collision collision)
{
// Call the ChangeScene method after the specified delay
Invoke("ChangeScene", destructionDelay);
}
// Method to change the scene
void ChangeScene()
{
// Load the scene with index 1 after the delay
SceneManager.LoadScene(1);
}
}
is there anything wrong with this code
what this does is
its in a gameobject
and whe you touch it
you get flung into the sky
you do in fact get flung
Can you type your entire thought out before hitting enter?
but it doesnt change the scene
sorry, it's how i type naturally
Yes and it's silly
First of all, you can just call a function with ChangeScene(). (I just noticed there's a delay, so what you have is fine)
Do you have a scene with index 1?
yes, it's listed in the build settings
Secondly, put a Debug.Log inside of your OnCollisionEnter to see if it's actually calling that function
For floats
Nm, forgot how invoke works lol
if you're trying to represent a field with a value using the inspector from a selection then use enums and resolve it at start (or onvalidate for SOs)
It didn't call the function when i used Invoke, but it did when I just called the procedure point-blank. Is there a way I can add a delay in the procedure, or would I still have to use Invoke?
Let me try using a coroutine.
You can use Invoke. Or you can change your ChangeScene function into a coroutine and add a delay.
Coroutine or timer
Most important thing is the debug log to verify that OnCollisionEnter is firing though
Because the launched into the air part is happening elsewhere. It doesn't prove this code is running
The OnCollisionEnter is firing, but the procedure isn't.
How are you sure?
I added a debug log in the OnCollisionEnter right before it Invokes the procedure. I also added on inside the procedure itself. The one outside outputted, but the one inside didn't.
Ok nice. Sounds good
Now, one more question, is the obejct with that script being destroyed anywhere else?
yes, it can be done pretty easily with uitoolkit's "DropDownField" by just chucking in a List<string> to it's choice = myFloatList property and all you need is to parse it back to float onValueChanged
No, it isn't.
or even better, use a popupfield and wrap the float in your own class
The object is never destroyed at all, actually.
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class scenechange : MonoBehaviour
{
public float launchForce = 10f;
private void OnCollisionEnter(Collision collision)
{
Debug.Log("collided");
// Call the ChangeScene method after the specified delay
StartCoroutine(ChangeScene());
}
// Method to change the scene
IEnumerator ChangeScene()
{
Debug.Log("right b4");
// Load the scene with index 1 after the delay
yield return new WaitForSeconds(2f);
SceneManager.LoadScene(1);
Debug.Log("should've loaded scene");
}
}
I converted it into a coroutine, but the code is back to not changing the scene again :/. It outputs "collided" and "right b4," but doesn't output "should've loaded scene."
It only works if the procedure is directly called, and doesn't if it's either called through an Invoke function or is converted to a coroutine.
I don't have any context before this message but if you are loading a new scene and this object is in the previous scene, this object would no longer exist when the other scene loads and so would no longer be running its coroutine
The coroutine ends when the scene begins to load anyway
well it sounds like they are expecting to see the restuls of Debug.Log("should've loaded scene"); but aren't
It happens at the end of the frame, which is after the debug, if you meant that
The whole scene isn't loaded either, which is the main issue
It outputs "collided" and "right b4," but doesn't output "should've loaded scene."
is what i'm addressing...but yeah if the scene also doesn't load then that's probably more important to figure out
Yeah, the debug would run even if the scene did load is all I meant. Since that happens at the end of the frame after the debug call
oh you're right and the message is actually misleading ๐
Ahh, I see what you mean now.
Yeah, it wouldn't log it in the new scene for sure
When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.
Oh it's the next frame! Good to know. Thanks
^ from the docs so i guess it's probably that and the solutoin is to use the Async one
yeah i didn't know any of this cause i've always just used the async one
ok thanks, i didn't know that the object deleted (though now that i look at it, it seems obvious)
Yeah, i guess it's less that the object gets deleted and more that the world it existed in no longer exists? but the end result is the same which is that the object is no longer running the coroutine.
But normally what Aeth said is right and what I was saying is wrong, just this one method behaves weirdly and you should probably use the async one instead
Does the scene need to be in the build settings to use Async or not?
if you want to load a scene it needs to be in the build regardless of whether you load it asyncronously or not
On my Player there are many Children. These children are basically their own character as they have their own components. However, only one is active depending on which which the Player decided to shape into. Now I want to know if there is a way I can refer to the current child that is active. This is what my scene view looks like:
I think I figured out the issue, just because I to explain it. Nevermind*
i have a little if statement to create coyote time and jump buffering for a platformer, but it makes it so if you double tap jump really fast, then you can do a sort of double jump boost to go higher. I do not want this to happen. How can I fix this? would it be by adding a very slight (0.2s) jump cooldown, or is there a better solution?
if (timeSinceGrounded < 0.2f && timeSinceJump < 0.2f && !isJumping)
The isJumping bool should handle that.
How is it set?
Then i don't understand how you could be able to double jump
Show the jump code
{
if (!isInputtingJump)
{
isInputtingJump = true;
timeSinceJump = 0;
}
if (timeSinceGrounded < 0.2f && timeSinceJump < 0.2f && !isJumping)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
timeSinceGrounded = 1;
timeSinceJump = 1;
}
}```
isInputtingJump gets resetted here:
{
isInputtingJump = false;
}```
It SHOULD be correctly stopping double jumping. Nothing seems like an issue here. Hmmm
Have you tried GetKeyDown instead of GetKey?
getkeydown only works on the first frame input
i want to allow buffering so i don't like using getkeydown for this
i found the issue
{
if (isJumping)
{
Debug.Log("grounded");
}
isJumping = false;
timeSinceGrounded = 0;
if (abilityCharges < 1)
{
abilityCharges = 1;
}
}```
I added this `Debug.Log();` line to check if the game was somehow detecting that the character is still on the ground after the 1st input
it is...
huh
Sorry, I forgot to ask earlier. What do you mean by Async Scene Loading?
SceneManager.LoadSceneAsync(1);
Is this what you meant?
yes, though if you read the docs you may find there's slightly more to it than that
Alright, thanks!
how are you detecting isGrounded() and in what update method is that code with the log? Update or ?LateUpdate
isGrounded used OverlapBox (2d) and this all runs in Update
sorry I meant FixedUpdate not LateUpdate lol
time variables are multiplied by time.deltaTime
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class scenechange : MonoBehaviour
{
public float launchForce = 10f;
private void OnCollisionEnter(Collision collision)
{
Debug.Log("collided");
// Call the ChangeScene method after the specified delay
StartCoroutine(ChangeScene());
}
// Method to change the scene
IEnumerator ChangeScene()
{
Debug.Log("right b4");
// Load the scene with index 1 after the delay
yield return new WaitForSeconds(2f);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("lvl2");
Debug.Log("should've loaded scene");
while (!asyncLoad.isDone)
{
yield return null;
}
SceneManager.SetActiveScene(SceneManager.GetSceneByName("lvl2"));
}
}
I feel I am doing something wrong...
does that compile? i think LoadSceneAsync needs a mode
so does LoadScene, come to think of it
oh no it has a default
don't mind me
then I think I see why it still detects the ground
it's a combination of two things:
you might get 2 or more Update frames before the rigid body actually moves (as it's updated in FixedUpdate which runs independent of the regular update cycle), so even with a pixel perfect ground detection you might still be detected as being on ground in the next frame(s) as the character hasn't moved yet
in addition, an overlap box check, depending on where the bottom edge of that check is relative to the character's bottom edge, might take a bit of an offset until it doesn't overlap the ground anymore
a quick fix might be to only allow jumping if your y velocity is <= 0
I don't think you need to set the active scene (it should happen automatically when you load the new one in single mode) but i don't think it should cause any problems
if you're still having issues, try hooking your code up to a button or something instead of triggering it from a collision to isolate some of this
thanks!
by "load the new one in single mode," do you mean "SceneManager.LoadScene("lvl2", SceneManagement.LoadSceneMode mode = LoadSceneMode.Single)"?
kind of, but the assignment you have there is the documentation telling you that's the default value so you're already doing that in your code
Oh. So just "SceneManager.LoadScene("lvl2")"? (Sorry if I'm not understanding ๐ )
rahhhh still not workingmf!!!
though you should use LoadSceneAsync
or you haven't actually gone anywhere
i did tho
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class scenechange : MonoBehaviour
{
public float launchForce = 10f;
private void OnCollisionEnter(Collision collision)
{
Debug.Log("collided");
// Call the ChangeScene method after the specified delay
StartCoroutine(ChangeScene());
}
// Method to change the scene
IEnumerator ChangeScene()
{
Debug.Log("right b4");
// Load the scene with index 1 after the delay
yield return new WaitForSeconds(2f);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("lvl2");
Debug.Log("should've loaded scene");
while (!asyncLoad.isDone)
{
yield return null;
}
SceneManager.LoadScene("lvl2");
}
}
or is the last line useless
nothing happens either way
well i would try this
ight
you see the logs? just once for each? make sure that your coroutine is definitely being started and just the one time
put a log after that while (where you had the extra LoadScene) too, you should be seeing that now
if you aren't i would imagine you'd have an error
basically copy the docs exactly (but with your scene) and make sure that works, then adapt it to your use case
i tried changing it from collision to just the defautl void Start() and it worked
so something fishy is goin on
Yeah something about calling it from the collision doesn't work, though offhand i'm not sure what. I would noramlly guess that it's being triggered repeatedly, but with OnCollisionEnter it shouldn't be (and your logs would show that clearly)
my friend says it might be because i have a while loop w/ no waits
nah they are wrong -- you just said yourself that it works when you start it in start
alright
the while will yield each frame that the scene is still loading
idea: collision enables a separate script which uses void start()
nah you don't need to get that complicated
have a boolean that you set on collision and check that in update
genius
see if that helps
it's possible that you can't trigger scene changes from a physics event, though i'm not sure why that would be and i can't find anything saying it
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class scenechange : MonoBehaviour
{
public float launchForce = 10f;
private bool isActivated = false;
void Update()
{
if (isActivated == true)
{
Debug.Log("Starting scene change process...");
// Start the coroutine to change the scene after a delay
StartCoroutine(ChangeScene());
}
}
private void OnCollisionEnter(Collision collision)
{
isActivated = true;
}
IEnumerator ChangeScene()
{
Debug.Log("Waiting for 2 seconds before loading the scene...");
// Wait for 2 seconds before loading the scene
yield return new WaitForSeconds(2f);
// Load the scene asynchronously
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("lvl2");
// Wait until the scene is fully loaded
while (!asyncLoad.isDone)
{
// Output the progress of the scene loading
Debug.Log("Loading progress: " + (asyncLoad.progress * 100) + "%");
yield return null;
}
// Scene loading is complete
Debug.Log("Scene loaded successfully!");
}
}
didn't work ๐
can you post the log output?
um did you do anything to your timeScale?
I know in a lot of cases parents and contraints work well for this but if i have a moving platform and my player is on the moving platform it's possible to adjust the position correctly via doing some position math in fixedupdate on the elevator right? could someone refresh my memory on that
i dont think so?
does it work without the 2 second delay?
well you know that part is working since the collision is being triggered/the coroutine started at least from the logs
yeah but idrk my friend is telling me to try random things
you should try specific things with specific goals in mind instead ๐
yeah hes just a bit
for instance isolating precisly where your code stops running (before the wait? after?)
no!!!
alright
Yeah, IIRC, you add the platform movement to your player movement . . .
would that just be having like a cached position that i set in update and get in fixedupdate thats added on?
or is fixedupdate after the movement happened
trying to figure out what exactly i would be wanting to add
it seems like the coroutine starts, but none of the while loop actually runs, which i guess takes us back to where we started (the simplest explanation for that would be if this object were destroyed in the next frame, preventing the rest of the coroutine from ever running)
another explanation could be that your timeScale is set to 0 so time isn't progressing and your coroutines aren't ticking...not sure what else
i guess the difference between last frame and this
You have to add the amount the platform moves each frame . . .
Yep, exactly . . .
ya ok that makes sense
i guess best place to grab last frame would be lateupdate then? im assuming update works too but
Use LateUpdate bc that's after the movement has occurred . . .
every . is a bullet going straight through my heart ๐ญ
don't take it personally, they always do that 
Haha, I thought you knew that by now ๐ ๐ ๐
im getting pretty pog in c# and a lot of unity quirks but my kinda math/physics knowledge is really rough
no high school education so fundamentals in that regard can trip me up
thanks for the help btw
Does a capsulecast 'hit' indeed hit against objects in the capsulecast's way? I'm moving objects directly into the "line of fire" of a capsule cast, and have print("Hit something"); inside the If(Physics.CapsuleCast) code, but it never seems to register a hit...
you probably want to start by visualizing the ray to make sure it's going where you think it is
If you need something to help visualize, you can use Debug.DrawRay to get an idea of the direction and distance, or mess with Gizmos for more accuracy, though personally I find Vertxyz "Debugging Utility" git project super helpful for this kind of stuff as it accurately visualizes all the cast shapes, their distances and when they hit something
how can i make the 0's just not affect the rotation instead of setting the rotation to 0
basically only rotate on the x & z axis and just ignore the y axis in this example :)
Quaternion targetRotation = Quaternion.Euler(1, 0, 1);
Just replace that 0 with whatever y rotation you have right now
OH ๐ im so dumb tyyy
and dont use targetRotation.y to do that
im not THAT dumb lmao
lol
i just realised that method does not work with the thing im doing
lemme try smth differed
yea it dosent work
basically i have a object that i want to rotate only on the x and z and that object is parented to an object that will handle the y axis rotation and since thats the way im handling it, the value of the transform.rotation.y alwase = 0 which means its the exact same result as just putting 0
Then use local rotation?
tysm i didnt even know that was a thing
can confirmโฆ why did i never use these
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that didnt fix my issue but i found out what DID fix the issue, basically instead of making the parent only control the y axis while the child controls the x & z i just reverted my code to before i tried fixing this and just made the parent controll all the movement and not only did this fix my one small issue, its also fixed like 90% of every other issue i had...
thanks for trying to help me with my whacky ass code tho, i appreciate it :)
I'm a newbie to programming, in the screenshot attached, the method is used to spawn objects randomly inside multiple squares precisely.
Can anyone help me elaborate the calculation made inside the method that I'm not able to understand a bit how exactly it works
They set the x/y value of the vector by adding to it a minValue and random value (from 0 to 4) and multiply that random value with another value (I think an offset)
Hey there. so I am experimenting with multithreading in unity and have this script to simulate a wave but I cannot get past the error:
UnityException: get_transform can only be called from the main thread.
Like I am so confused...
use ijobparallel for transform
not code related but i cant find anywhere else to post this.
is there a way to bring the changes from your latest commit in github desktop, to uncommited changes so you can discard some of them?
My question is, I don't understand how this method helps spawn objects within specific radius position ๐ญ
Please do help me understand in the easy way possible since I don't come from CS background
A DM explanation is much appreciated and truly helpfull on this so that I can share more details with you ๐ญ๐
Note that transform.rotation is a Quaternion, not euler angles
So using rotation.y doesn't make sense
hai, I need help putting on an fbx file of a model into my game, but it seems I cant simply drag it to the player's sprite or add it as a new component, how do I go about doing this ?
is there a way to only revert some things? i dont know how to say this... i want to revert an unpushed commit, but still keep some of the changes
Drag & drop the child mesh of the FBX file into the inspector of the object you want to add it to
It will add a MeshFilter and MeshRenderer for you
Sprite doesn't work here, as it's a mesh not a sprite
!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.
It basically takes a minValue (like 4), then they add to it a random value (From 0 to 4) which should be the min and max value of that radious in x and y, and then multiply it for an offset (like 20)
This is at least what I understood
May be wrong tho
Thank you for the explanation ๐
sry, what would the child mesh of the fbx be ?When I click on the fbx, I only get these options...
Mivalue is an offset itself from the point 0,0
@languid spire i dont understand the message !code from unity dyno bot what must i do now
๐ 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.
also, i just dragged over the fbx to the player and like pinned it in front of the capsule ive been using as the player, and it seems to work. But still curious on ur way to do this
i had to adjust it tho to be overlapping with the capsule
Show the FBX in your project browser window
Yeah dragging the FBX itself works too, if it's the only mesh in it (I think)
read what it says and do it. if you want to post a large block of code use a paste site, if you want to post a small block use the inline formatting
If you click the arrow on it you can see the child meshes
oh sry
So yeah you can drag the correct mesh from there if you want
This is a code channel btw.
oh, sry, which channel would I go on? Also, it seems the first thing I tried included the colors and stuff, so ill just stick to that, ty !
#๐ปโunity-talk Is ok for this kind of stuff
that counts as a large block'
okey wait
doesn't matter.
you decrement currentAmmo twice for every shot
you check input in FixedUpdate which will be inaccurate
I have a simple animation on a player charachter in my 2d game, during that animation i try to call an animation event method that detaches one of its children. For some reason that child object occurs in random positions after detaching. The problem is not in colliding with other objects (i tryed to debug.log any collision) and not in animation (child object jumps even if i just call detach method as a regular method, not as animation event) and it's not about velocity (i tryed to set it to 0, but it had no effect) So, why it can be happening?
Hmm, try using a coroutine with WaitForEndOfFrame and then detach it?
I want to enable the footsteps after waiting for 1 seconds to prevent spamming the auidoclip. It starts after one seconds when I move but It does not stop when player has no movement. https://hatebin.com/mbcmpncfow What am I doing wrong here?
Stopping works when I log but the coroutine does not stop.
First thing I noticed is that you aren't setting isFootstepCoroutineRunning to false anywhere
yes you are right. Where do I set it to false? I am confused.
Probably at the end of the coroutine and also when you call StopCoroutine
Did those but it still does not stop when there is no movement.
I'm also not 100% sure if caching the IEnumerator in footstepCoroutine works or not. I usually just do StartCoroutine(MyCoroutine())
Where are you telling it to stop the audio?
footstepCoroutine = PlayFootstep();
pretty sure that wont work as you expect
footstepCoroutine = StartCoroutine(PlayFootstep());
Well when coroutine stops it disables the source no?
No, that doesn't magically happen
I do this in update then
dont start coroutine in update
not a good idea
Unless it's in an if statement
it is in an if statement.
You need to manually stop/disable the audiosource when you want it to stop
hm I do that in the second if in update maybe
after stopping the coroutine
Okay it works now. Wow
Show your updated code just to be sure
Pretty sure you have to change `the second condition in this: if (!_player.isMoving && isFootstepCoroutineRunning)
What if the coroutine stops? Then you can't stop the audio
if(!_player.isMoving && footstepSource.enabled) would make more sense
For stopping the audio, I mean
Maybe make a 3rd if-statement
if(!_player.isMoving && footstepSource.enabled)
{
footstepSource.enabled = false;
}```
Can you explain this one? I did not get it
Like how does it stop if I keep moving?
I thought stopping the coroutine would stop playing the sound. That was my mistake as you said. Gotta be more careful T-T.
Thanks for the answers
why would it stop playing the sound
the coroutine is not your audiosource
stopping it wont stop the audiosource
Sup, i use Handled.Vibrate(); to make vibration on phones, but its too long, is there any other way to do it?
how hard is it to learn saving 1 - 10
what saving?
with player prefs? very esay
it was hard to make binary formated one.. 7 ig, but now its ez for me
Saving Data in Unity, A complete guide to PlayerPrefs, every function covered, the easy way!
Links to all content (twitter, Instagram, shop, discord etc)
https://linktr.ee/DestinedLinks
Any comments or questions welcome. Enjoy the video!
0:00 Introduction
1:37 Setting up tutorial in Unity
5:26 Saving Strings
10:30 Saving Floats and Ints
15:50 ...
PlayerPrefs.SetInt("saveKey", intValue);
Player prefs are ez to hack u know...
how would you regain your save data
GetInt("saveKey")
i mean physically in the build
same
like how would you get it and enter it to regain your save
Player prefs are saved on PC
the same way i wrote it
SetInt/GetInt (save/load)
but how do you do that in the game itself
maybe make player able to save its own custom data?
nevermind ill figure it out once i get home
You are right. I understand now thanks.
someone?
you can only tell the phone to vibrate
not how long to vibrate
this is usually tied to the phone OS and nothing you can do about it
oh ok..
But this problem appears ?
These "strings" are different ?
I'm so sorry
T-T
Hi, can you make code run every frame without using Update()?
yes, Coroutine
Ok thx. I wanted to avoid this because checking a bool every frame seems like a waste of resources, but I realized I'll be destroying that object very soon anyway so it won't be a problem. Out of curiosity if that object were to stay in the scene forever, how big of an issue is that?
You can use a Coroutine which waits for a frame if you use yield null. Additionally you have Task methods that allow you to delay for specific milliseconds. lastly Unity 2023 has awaitables, which allow you to await until the end of a frame.
if checking a single bool every frame is the worst of your problems you are doing very well indeed
Checking a boolean has no effect on performance and you should not worry about performance in general except for the usual "don't use find methods every frame" and such.
.NET is very performant, and polishing performance could be done later. Even then you are better off benchmarking code to figure out what actually needs to be improved
If you really want to improve performance, you could try and lift the work of the garbage collector. There are method and features that allow you to manipulate memory better, but this is a very advanced topic.
btw, Input.mousePosition is a Screen position, you need to convert this to a World position
It's for inventory, on canvas so it works, but thanks.
This is all I have right now so I don't have performence issues yet xD
if you spawn those things often you could also look at object pooling. It's a simple yet efficient way to improve the performance of your game.
Hi everyone, is there more effective way to get access to method from other (non-static) class than inherit from it?
What do you mean get access to a method from it?
Like call it? If you mean just being able to call it, the โbestโ approach is highly dependent on situation.
Hi, why do the wheels seem "laggy" when I focus on the car? When I'm not focusing the car they work fine.
(I'm updating their position in the Update function using raycasts)
Hello, I am wanting to grab a variable known as playerScore and read it in that file in an if statement. Unlike other languages where you can just import them. I am unsure of how I can properly import this variable into another script to use in my update function.
Been googling for 3 days and nothing i've found has been working so far
does anyone know why this is ending up behind the canvas when i start the game
The Unity way of doing this is to add a serializable reference in the class that wants to access the variable and then to assign to that reference the object whose variable you want. Then you use a method like getvalue() or a public get property to get the value of the variable.
Because it's a sprite renderer.
To show images in the UI use the Image component
Ah okay ty
yeah, for example
Please provide more info about what exactly you are trying to do.
when i drag my image into it it rescales how do i make it it will be the scale of my image
i got it
Is there a less messy way to create a Back Up copy of a script so Unity doesnt get confused with the duplicates and i dont have to always go in a change the class name inside VS as well?
What reason would you need a backup copy of a script?
Use source control.
Are you using version control? Learn to use version control
If you just want a quick a and hacky way to do it then just rename the .cs to .csBAKUP
Thats what i was wanting sorta, i cba to use Github at this stage
I have a player with some basic movement and animations, and I changed to the "new" input system because I thought it would scale better, and just to test it I tried doing the same thing as before, but if I reset the animation when the direction vector is (0, 0) it will always trigger and my animation will not appear, and even if I put it at the start and let the other 4 if conditions override it they only last a single frame, and I'd like for a hypothetical OnMoveEnd function, so I can disable it when the key that is being held down gets released
Its obviously not a great way to maintain your source control history, :), but I must admit I've done it occasionally.
my player input is set to "send messages", is there a function in any other setting that allows this
Honestly using git for source backup and version control for a solo project is really easy and youโll never go back once you figure out the two or three commands you need.
This is an animation problem not an input problem
You need to set up your Animator for this stuff and use StateMachineBehaviour for the transition notifications
I checked that on google but wasn't able to find the notification for that
could you tell me what to set it to
Well, for example when I have script which generates new room like in rogue-like and it uses method from class which contains all data about sample rooms (what doesn't allows to make it static). Do I have any other ways to get access to this method other than inherit from it? In that case I have to attach all gameObjects which my parent-class does but it is totally unnecessary
I mean to say that these were confusing me and I couldn't figure out what to use to invoke a function or something
You donโt need to inherit from it. Just have a reference to a public method in your data class and call that method using the reference.
Inheriting from it in this case is a bad idea.
You're on the wrong track completely
Why are you trying to pick a function from PlayerInput
You'd put your own script there and a function from your script
I have no idea which event this is for though
Sorry but I think i dont understand what u mean
ah I see
I thought there was a built in thing for it and I was looking for so long
all my functions were private
thank you
If I want to reference data class have to be static
or i have to reference to a obj
No, either make the data class inherit from monobehaviour or scriptableobject and then you can drag a reference to it to your generator object in the inspector. Then you can call the method on that object.
I think you should do a c# tutorial in isolation from Unity to get some of the fundamentals.
mkay, maybe I should.. Anyway thx
can any one give me some suggestions on level desing
and a level that can be parkor able
for 2d
Not a code question and also highly dependent on your game design.
So when I make the variables I should do something like: public float playerScore { get; set; } = 5 and then use something like playerScore.get() to fetch its value?
btw the mario maker community will have extremely deep knowledge when it comes to answering your question
no
ouch
the most common pattern will be:
public float score {get; private set;}
the point is to keep the setter protected by restricting its access
but allow more classes to read the value
But would the method be correct? playerscore.get()?
you donโt need to call it like that
oh?
ok I experimented for a while and I can't figure out how to make it only end when the key is released, not when it finishes animating once. I want it to animate the movement on loop until you release the move key, not once it animates once
you can do
float myVariable = score + 4;
you do not need to explicitly call .get, as it it a property
you can also do:
score++;
which calls the setter and getter, each
get and set are keywords. they do not need to be written like methods, if that makes sense
Yeah but you donโt need .get. Properties syntactically act like variables. So you can just say whatever = property. No .get().
also
public float score {get; set;} = 5;
is kind of pointless, because that might as well be made a non-serialized field.
youโd only do that when you want to actually add code
like
private int _score = 5;
public int Score {
get { return _score; }
set {
if (_score == value) return;
_score = value;
OnScoreChanged?.Invoke();
} ```
in this case, Iโm actually doing stuff whenever score gets set. So it has a backing field (_score), and I can do stuff whenever it gets set
eg Score++;
this will set _score to one higher than the current value, and then invoke OnScoreChanged
@worthy merlin understand?
Ooooooo thanks will they have knowledge regarding vertical levels
I hope so lmao.
So I have it setup with that now in my LogicScript however in my PipeMoveScript the playerScore is not recognized within my update.
void Update()
{
if (playerScore >= nextAssignment)
{
moveSpeed *= speedPercentIncrease;
nextAssignment += 1;
}
is playerScore defined in LogicScript?
I am working on a game with like a confined vertical platforms and you need to parkore to get to the top it is my first game I am working on it Is just to learn unity but I still want to make it something playable
Hi guys, I have a Resource folder with a couple hundred of prefabs. I want to loop through all of them and change the materials GPU instancing to "true". How do I access the actual material files for each of the game objects?
the materials are all over the place in my project and many of them i do not want to change. I only want to change the ones that belong to the objects in my resource folder
you cannot tell which material belong to the object and which not
could i not load the prefab and check the renderers material list for this?
the problem i have is that the material on the renderer is only an instance
Hello, any ideas on how a katana attack can be implemented on unity? i thought about making a script on the enemy object and it reduced its hp oncollision with an object weapon
I would have the weapon affect whatever it hits.
how would you do that? i mean lets say we use the oncollisionenter method, then what?
Get health component of whatever it hit and do its thing.
Hello, can someone explain why this debug is giving me this error?
Did you put: public class Something : Mononehaviour (<- This)
yes
Got it, you need: using UnityEngine.Ui;
Put it with the other using stuff
And you should be good
Np
yeah, there are a bunch of namespaces that Image can come from
Hi, I don't even know if this is where you ask this type of question. I have this problem, I've been learning for about 4 days just how to make games, I'm following a tutorial, but my character looks like this when I jump on the wall, so the bug appears and the player manages to get around it and jumps off the walls. I've already reviewed everything and I don't know what else to do...
I do not understand what the problem is.
"but my character looks like this"
is this a visual problem? a gameplay problem?
like a visual thing, or is this gettin stuck on colliders you dont think it should be?
classic velcro wall?
Both, it visually looks like this sometimes if you just jump on the wall, and it also affects the game, since if the player wants to "cheat" he can keep jumping on the walls....
yup, velcro wall
pretty sure he addresses that in the vids no?
on ur colliders/rigidbody you can use a low friction Physics material
and it'll slide right off
No, I think it must be the collider. tilemap collider 2d. but I don't know what to do. He gets shaking sometimes too, when you press him against the wall
okay, so the problem is that you're getting "stuck" on walls
it shouldnt be shaking at all
let me check my unity i was follwing the same tutorial lol
with the deadpan german guy right?
As I don't speak English, I'm translating, maybe they're not extending it hahah, I'll send a video
Yeah its defined with public int playerScore { get; private set;}
Srry for the delayed response. in School rn
ok but how are you moving the player
whats ur first language?
portugues brazil
have you placed the terrain and background on seperate layers?
you are not moving your player using the rigidbody but its transform directly, that is the root of all these issues
I'm following the tutorial hahah
he had no problems with his
So to solve it I would have to change how the character moves? I thought there was something wrong with the collider jkkk
the issue is that while iterating over a collection, you are removing items from that collection, which messes up the iteration. https://stackoverflow.com/questions/7193294/intelligent-way-of-removing-items-from-a-listt-while-enumerating-in-c-sharp
then PipeMoveScript needs to access a playerScore, which is on a particular instance of a LogicScript
you should also move the "getcomponent<enemyManager>" to outside the loop, at least assuming there is only one manager
if you just write playerScore, it will check its own class for that variable, but wonโt find it because thatโs not where you put it
why doesnt this work
Spectating.activeSelf.Equals(true);
i debugged it and after that is done it still is false
did you actually check the value of activeSelf
oh, I think I see what you're thinking here...
Spectating.activeSelf.Equals(true);
Debug.Log("Spectating is: " + Spectating.activeSelf);
yep
that just checks if activeSelf equals true
it doesn't mean "set it to be equal to true"
oh it doesnt
yes. Equals is defined for every single kind of C# object
it's used to test if two objects are considered equal
k thanks
activeSelf is read-only
i fixed it
just use SetActive to change the active state of a game object
when does it happen?
Seemingly randomly. When I add a component, when saving a prefab, when switching to another software tab, at any moment in any scene, etc..
Sometimes happen many times in a row, sometimes doesn't happen for an entire day
i think it could be a corrupted file, lack of memory or an script that might crash it idrk
I'd delete the Library folder and let everything re-import
see if the editor behaves any better after that
it'll take a while to do that
the editor will forget a few things, like which scene you had open
A few hours?
like 5-20 mins depending on your pc / project size
well try that first, then come back ๐
Sure
you are using unity 2019?
Yes
anyone got a good yt channel that teaches unity in different parts and explains it rlly clearly?
does not exist but !learn does
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
unity learn is more like txt / video / project type lessons
structured course *
there ya go ^ its that
but Sebastian is definitely not for a rank beginner
so you wont be watching unity learn.. more like engaging, reading, watching, doing
that series is pretty good for beginners.. it helped me get concepts of variables methods etc from the first few videos..
but i agree as he does standalone projects they're pretty code heavy and he doesnt explain much
Sebastian is very good, but he expects a lot of thought from his viewers, something which appears to be sorely lacking nowadays
yes agree'd, some of his stuff he forgets to show bits of code that makes the entire system work.. so u sometimes have to go solo and figure out that missing piece ๐
imo, he's explaining things quite clearly, but that might be bc im already doing python at skl so some of the terms r linked
yea ull be good using both
everyone wants a magic 'Make my game' button
nah, i want a "make me understand" button
awesome! lol
nice try, doesn't exist either
btw is c# " or ' sensitive?
oh and !ide not sure uve done this
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
like does it matter which quotation we use for strings?
but make sure ur stuff is configured correctly before u go hamm on the code
i think " is encouraged
yes it matters, ' is char " is string
i had a unity arc for like 4 days and then i said "nah i aint doing this" so i already got this stuff
but straight forward
basically like python
yes pretty much
Python and c# are significantly different in many ways. It's one of the more difficult language jumps.
But of course most programming concepts are the same. There are variables, loops, condition flow, etc
negative
i made a bot with python and i had enough.. i much prefer c#
i was talking abt the case sensitive part
is it similar right?
aren't most langs case-sens lol
i mean similar as in both are languages that can make stuff..
Nothing
The method returns nothing
void is a special type that means "nothing"
well i mention that because 5/10 problems i see ppl with are just simple spelling errors
you can't create a variable of type void
sebastian uses void to make a function, what does void do in that?
if ur function u write doesn't need to return anything back then its void
you don't use void to "make a function"
void is simply the return type of the function
public void Whatever(int parameter) { Debug.Log("The value of the parameter is: " + parameter); }
farts
this declares a method (a function that is part of a class) named Whatever
it takes one int parameter..named parameter!
and it returns void, meaning it doesn't give you anything back
oh i see
Every method declaration must have a return type
when would u need to use void?
when your function doesn't return anything
perhaps take a c# course
int AddNumbers(int a, int b)
{
return a + b;
}
void SayHello(string name)
{
Debug.Log("Hello, " + name + "!");
}```
void doesn't give anything back.. it only takes in the string and Displays it with "hello" attached
int is an integer of course.. so that function AddNumbers can take in two ints.. and return back one.. (in that case its just adding them)
and both of those are private
T AddNumbers<T>(T a, T b) where T : struct
{
dynamic aa = a;
dynamic bb = b;
return aa + bb;
}``` ๐คฏ
how would u call them, would u just do "int AddNumbers(1, 2)" ?
to call the first function
btw ik that u dont need to put 1 and 2
u can put any numbers
using UnityEngine;
public class Example : MonoBehaviour
{
void Start()
{
int result1 = AddNumbers(1, 2);
Debug.Log("Result of AddNumbers: " + result1);
}
int AddNumbers(int a, int b)
{
return a + b;
}
}```
anytime u needed those two ints added ud just call it like normal.. in that case we declared a new int called result1 and set it to be w/e that function returns
so result1 equals 3 when it runs
;
yea basically
alr ty
void Start()
{
int number1 = 1;
int number2 = 2;
int result1 = AddNumbers(number1, number2);
string resultString = "Result of adding " + number1 + " and " + number2 + ": " + result1;
Debug.Log(resultString);
}
string resultString = $"Result of adding {number} and {number2} : {result1}" ๐
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Hey all!
I uploaded my unity project to GitHub so I can work on it from multiple devices.
But this only worked if I used a .gitignore which ignored some of the larger directories in the project folder such as Library.
But if I clone my repository on my other device, will unity project still work? Will those folders auto generate from the editor?
Thank you!!
yup
yes
Thanks! Was I right in assuming theyโd autogen then?
yes, you could have tried this in the time it's taken to ask this question
I couldnโt have ๐ my other device is back at home and I donโt go back till tomorrow. Currently visiting parents and I created the project here on my laptop
I guess I could have tried cloning it into a new repos
Either way, thanks!
where can i find the link to setup vidual studio code so its not all blue?
!vscode
cheers!
odd, I always thought the point of having a laptop was to take it with you wherever you went
I do! I have my laptop with me here and my desktop back home. I made the project here but want to be able to work on it on both
Though I realize now that I guess I could have cloned the repos into a different folder on my laptop as a test
Either way, the assurance helps
Hey Ima have my first game be a turned based movement strategy game where you pilot your character to explore all 3 duegons or sum and then have them have keys and when key = 3 u can do the boss battle ig how does that sound instead of an rts to start ๐ AKA a tactis engine game ig
no, you miss my point, tomorrow when you get home you will have both your desktop and your laptop, so it's simply a question of connecting your laptop to your desktop in order to be able to work on your project from your desktop
no cloud required
Very good point. I just like GitHub because the cloud backup aspect and version control is nice
Though I totally see what youโre saying
Is unitys source control better than GitHubโs? Never tried it
I didn't enjoy using it when it was still branded as Plastic
Fair enough ^^
Lots of weird problems with the editor integration
I could not trust it to work correctly
its hot garbage
if you really want a good laugh (read cringe) install the Version Control package and then go and look at the source code
Unity still trying to compensate for bad investment, kinda funny they are beating a dead horse at this point. No amount of "in my face" about VC in hub is gonna make use that trash
it's rubbish, worse than that, it's dangerous rubbish because it lulls unsuspecting users into a false sense of security
yeah exactly, the ones who come here and have a problem is usually unity's VC and not git, very rare you get git problems
git is great, when you take the effort to learn it, in the wrong hands it too is dangerous as we see too often here
this might be a confusing question but can a class be inside of another class?
yes
not a problem. you just reference it as MyClass.OtherClass
would u call the class the same way u call a function?
You can nest many many classes, should you ? prob not
I would say, you probably want to avoid it.
I'm not sure where to ask this.
Does Unity Version Control have an equivalent to Github Issues?f
And Can I make a Project Public?
check the docs?
its not very intuitive system
your best bet is to ditch that mess and just stick to Github + git
good to know. Thanks
Basically yes. You access the inner class via the outer class
pretty sure a UVC project cannot be public
i see, alr tysm
Hey guys. I have a question. I have a footstep sound that is 2 seconds long. One step starts at 0 and the other at 1. Which leaves the last second empty. I have this code here that handles the audio source responsible. I used coroutine because I wanted to prevent w spamming and the sound. I put a delay to stopping time as well. The script works what I want it to but there is a problem. I want it to complete the footstep if its already started and not immediately stop after the delay. Do I need 2 footstep sounds or can I do anything in the script? https://hatebin.com/adejjjcfdp
An Issues page is still useful internally
not saying it's not, just answering the question asked
Ah, right, I literally only read the first half of their question and then my brain just... stopped. I didn't even realize there was more afterwards
I think it's the f typo after the question mark, my brain just went "Yep it's a float" and stopped reading
rofl
Ok I deleted and reimported the Library folder and unfortunately it's still doing it. I deleted a component on a prefab and unity froze. Maybe the problem is when the project saves but I'm not sure. (and only happens in the editor)
does your version of unity work fine with blank/new projects ? try making a copy of proj and open it with another version of Unity?
Doesn't converting a project into a newer version of Unity potentially cause errors?
sometimes, but you are doing it on a copy so it doesnt hurt
minor or patch version change, usually not
Unity does not support project regression
ya if you know what ur doing some stuff can be fixed, by manually messing with the manifest
export/Import if you want to regress, it's the only sane way
as long as you don't go back to a version that serializes your assets differently, you'll...probably be okay
wink
Yeah I can try that, it's just strange the log doesn't say anything about the freezes
wish I knew this years ago when I had to fix a 2020 project back to 2019 . I was infant back then tho
well if its frozen how can it output any information
also did you try a new project to make sure it isnt your Unity version ?
I'm trying to get a ui object to follow the mouse, so I have this
void Update()
if (icon_dragging)
{
icon.rectTransform.position = Input.mousePosition;
Debug.Log(icon.rectTransform.position);
}
}
and it's printing out the mouse position, but the ui object isn't moving at all
So basically you have 2 footsteps in one audio file and want the currently playing footstep sound to complete when the movement stops?
Just have 2 separate audio clips and play them alternately.
Also I believe there is no need for any coroutines here or (de)activating the audio source all the time, just check the methods and properties available for AudioSource, you can change the clip and call PlayDelayed(delay_in_seconds):
https://docs.unity3d.com/ScriptReference/AudioSource.html
I feel like I'm missing something obvioous
are you sure you don't want to move with .anchoredPosition ?
like actually reading the RectTransform documentation and seeing how to move a RectTansform correctly?
ok please don't be rude. I read the docs
I'm still not clear on the difference between anchoredposition and position though
and switching it to anchoredposition didn't seem to do it
All right thanks. Is it common practice to do footsteps like that? I mean using 2 different sounds for right foot and the left?
yes, its better than 1 sound
yeah but I'm not sure how to implement it. this doesn't work
icon.transform.SetPositionAndRotation(Input.mousePosition, icon.transform.rotation);
I use more than 2. Using random.range to draw from an array or if it's a bunch of actors I will build a few sequences of randomized ones
I've been using this version for years and only did this in the last couple of months. I suspect it's a package from the asset store that it's doing this, maybe, but I have no real reason to belive that
I will write the whole thing using Audiosource methods then. And figure out how to play them succeedingly.
[SerializeField] RectTransform rt;
private void Update() {
rt.position = Input.mousePosition;
}```
yeah but that's a regular gameobject right? mine is a ui object parented under the canvas
does that make a difference?
Nope
That is a ui element
Since it is using rect transform
the "regular object" is the one with the script
not relavent
GameObject icon_obj = new GameObject("icon");
RectTransform trans = icon_obj.AddComponent<RectTransform>();
trans.transform.SetParent(transform);
trans.localScale = Vector3.one;
trans.anchoredPosition = new Vector2(0f, 0f);
//trans.sizeDelta = new Vector2(150, 200); // custom size
icon = icon_obj.AddComponent<Image>();
gameObject.AddComponent<BoxCollider2D>().size = trans.sizeDelta;
this is how I declare it
is something in here messing with the code or something? like the anchoredPosition or the parenting?
You're adding a recttransform?
btw recttransform can just be casted from transform
RectTransform trans = (RectTransform)icon_obj.transform (assuming your object does have RectTransform)
I figured it needed a recttransform to be a ui element
Seems like what you want is a prefab...
Because doing it this way seems like it's breaking things
it becomes Rect element usually if its spawned as child of a canvas
also yeah just use a prefab it and instantiate
at the very least, a prefab would let you play around with the settings until it behaves right
https://github.com/Just1n12354/MyGameProblems
The coins are not being saved, can everyone help me
wher
SaveCoin is blank
Yeah lol?
No, not smart enough
But it may have to do with SaveCoinUpdate being empty
And CoinToString never being called
void SaveCoin()
{
}
void SaveCoinStart()
{
}
void SaveCoinUpdate()
{
}```
help my coins arent saving
Also this should 100% be its own class
Man people will do anything to avoid using a pastebin huh
Did u copy and paste the code?
never noticed this built in functionality in github
can enyone help me?
Just ask
read the link ive sent
How could I store all the base materials of a object and replace all of them for another material for a while and them back to the original ones?
They were saying you should just say your question, and yeah, we may be able to help
you could just store the .materials property of the renderer
here
the array you get is a copy; it won't change when you replace the materials
you clearly have a copy of this class method
Why does the beam go further than its range?
Why did u copy the method so many times?
It says u defined the same method like 5 times
I have srqched that this does return an array of all the materials, but how do I assing one particular material to all the material slots?
Those line numbers!
just tell me how to fix it and ill be going
Remove the methods that are copied
Store the array into a variable. Assign the materials into the array. Assign the array back to the materials property.
only use 1 method?
oke
The array the property returns isn't the array that Unity is using to store the materials. It's as new copy every time you get the .materials property.
So modifying its contents directly won't do anything
renderer.materials[3] = ...
more to the point, why are you trying to do multiplayer when you obviously do not know c# basics?
this sets index 3 on the returned array
thanks
which doesn't do anything to the renderer
yes perhaps learning basics of c# before you try to Mod anything..
You have to implement those methods
Ur deriving from a interface
Helping for modding or decompiled code isnt allowed here
Meaing you HAVE to define those methods that are in the interface
So I have to get the array from .material, save it as a variable, modify the array and store it in other variable, and give the modified array as the new .materials?
Correct.
And if you want to remember the original materials, store materials in a field before you do that
witch one
bold of you to assume they know what an interface even is 
I presume this is some kind of gorilla tag mod
if i'm reading this corrrectly, i believe what you are doing is casting a circle 5 units from the origin of your guy, where the circle has a radius of castRadius. i think that what you want to do is cast it at a distance of 0, with your cast radius.
I would hope so
yes, which sounds wrong
Sounds like you want:
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircleAll.html
Or if you want to use a specific collider:
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCollider.html
Thank you, I hadn't noticed.
i think using a circle collider might simplify things for you? https://docs.unity3d.com/Manual/class-CircleCollider2D.html
ok I switched everything to be prefabs instead of dynamically generated
but it still doesn't move
the debug says the values are changing
but the inspector doesn't
did you show your object hierarchy?
are you sure you referenced the correct object?
i'm getting a null reference exception now on icon.sprite = sprite;
even though icon is referenced in the prefab
Icon is an Image component
so it has a .sprite property
icon is null
that's the problem
but I can't see why it would be when I've given it a reference in the prefab and I'm spawning the prefab
you have to spawn the box and then get its icon.. if i think im seeing this right.. you can use a reference of something inside the prefab.. i think ur referencing the prefab from the project window. and not the instance of hte prefab that u actuallly spawn in the game
is that right?
ok nvm the null reference exception was unrelated and i solved it
but the image still doesn't move
I have a ui button that calls a function on an event trigger. On the same gameobject as my button, I have a script with a boolean member. Is there a way to either call a different function based on that boolean member, or to call a function with that boolean member as a parameter, while keeping things mostly in the inspector?
you still havent answered my original q :\
let me test that
How can I access this parameter?
Google didn't do a great job explaining this; Does a static Variable not get reset whenever I reload my scene?
I got a playerScore variable and despite the scene restarting it starts on 10 instead of 0
Click on it?
from a script
Your static variables have no knowledge of what the scene is. It is a value associated to the type, not an instance
Show the script?
Does the DoThing() method have a bool parameter?
U cant access parameters from a method?
Yes, I want to be able to change what gets sent as that boolean parameter within a script
Hmmm. guess I should find a way to fetch a variables data in another script without static then
When the method is called do some internal logic instead of trying to change what parameter gets passed into it
Have a field on the class thats a bool and check it that way
Basically I'm trying to create a "latching" button. When clicked, it calls a function. When "unclicked", it calls a different function. My boolean parameter was just an attempt at a workaround.
U shouldnt be trying to change method parameters via the inspector IMO
Oh u should look into the OnPointerDown and OnPointerUp
When the mouse is clicked and Released
yea. lol thats weird.. thats more like a simple way.. if u want a button to passing in false or true.. or w/e u could just call different functions instead
Sorry, not unclicked. When clicked, one function, when clicked again, a different function.
So I'm tracking, on the button side, whether the button is latched. If latched, clicking it calls a different event
And unlatches it
Yeah you should do internal logic on the methods themselves to check the current state
You can still use the UnityEvent for whatever method. That method just has to check whats going on
if ur doing stuff like latching it and tracking it.. ur logic should know everything..
no need for that exposed bool..
Yeah?
thats for the inspector
When its via the Inspector thats pretty much a constant parameter for the method
like if ur wanting a quick button to do one thing or the other.. u can tick the bool (in the inspector) for different behaviours
but if ur using the same b utton to do many things.. ur logic should just keep up with that
agreed
Yeah I don't actually like that workaround where I'm changing the boolean value getting sent as a parameter. My whole goal here is to keep everything decoupled and have a button with an extra state (whether it's latched or not) which changes the event called based on whether the button is latched, while making use of the unity event system
Again
I know how I could do this with additional references, but I was hoping to have this latched button object which is just as simple as possible
You dont need additional references
Just have a bool that checks if its latched or not and that method can have a simple if statement
That class just needs to be on the same Gameobject as the button
private bool isButtonPushed = false;
// Method to handle button push logic
public void ButtonPush()
{
if (isButtonPushed)
{
}
else
{
}
}
public void ToggleButtonState()
{
// Toggle the button state
isButtonPushed = !isButtonPushed;
// Call the button push method
ButtonPush();
}
u call the same method each time.. and let ur logic do the handling, edit: you probably could call the ToggleButtonState() and that would handle latching or w/e
no reason to have that variable exposed if ur just gonna pass in a variable to change it
thats all im sayin
Here's where I lose the convenience of Unity events though. For a normal button, I can just add the function call that happens when the button is clicked. Boom, easy. What I'm trying to accomplish is the same level of convenience using my latching button. And I'd like to keep the "latched" boolean on my button object, because I visually change the button based on whether its latched
That's what I'm becoming convinced of.
lol, yea that tickbox is for the developer
Forget the tickbox
not the code ๐
i cant forget it.. ur logic was all based off it
did u ever share ur code?
It was pseudo code
u want a controller script for the button
he didnt even name the class
this isnt how u should be thinking
u want the script thats controlling the button to know if its latched or not
and keep up with it
if something needs to know the buttons state it can ask the script
Yeah thats why i said if im reading this correctly?
not the button object
When it shows (instance) it means that if I were to modify the material, it would only affect this instance right?
And so a reference to that button script needs to be given to the object whose function I wish to call
changing stuff on materials gets iffy
Theres a class that button derives from
or the object whose function you wish to call.. could ask the utton script
so have a reference to it
it would know ALL the states of thebuttons
I cant remember the name but u can make ur own button with extra functionality if u insist on no references
Yeah, I just wanted to swap the materials to something transparent while they do sorta of an spawn animation; but still not sure how to do the full thing though, so I have been trying different approach for the last few days
modifying the material itself can be tricky because shaders are more complex. But swapping from one material to a different material (both of which are already made) should be fine
https://hatebin.com/lkwyqmnjhq @wind raptor
netcode
it'd be something like this.. the button script handles all the states the button can be in
This is becoming more of an intellectual exercise than practical at this point, but yeah a reference to the button may be necessary.
One last attempt at a workaround. Can I have a serialized field for a function call from a different object? So that I could drag in an object and specify the function, just like it is done for unity events?
Okay yeah, but in your switch statement there, can I have callbacks to functions that were added in the inspector?
never had to use it.. not really modifying my buttons beyond making them interactable or not
ya u can
you can use the UnityEvent system i believe
to invoke but idk about any of that
Theres more classes to derive from then just The MonoBehaviour inside of unity
Hi, I'm applying some forces to an object to make it move in the FixedUpdate, should I multiply the forces for Time.deltaTime? When should I do that?
check your units, and all the math will make sense
You would do that for moving a transform
But AddForce applies deltaTime already for the modes that need it.
Velocity is meters per second, so it doesn't make sense to use there