#π»βcode-beginner
1 messages Β· Page 279 of 1
As I thought, and what is the public variable you are trying to drag it to in your script?
Okay, and your variable is of type TMP_Text, right?
yes sir
Open up the DMGNumbers prefab and send a screenshot of the hierarchy
No it isn't, that's the shared parent class between both UI and 3D text
it works for this
TextMeshPro is the world text
TextMeshProUGUI is the UI one
TMP_Text is both
is this enough?
hey guys its me again and i have everything working now i just need to check if the walking points are valid whne thyere random so my solution was to create a ray cast and if it touches the cube then its valid because it can reach the point with no obstacles and basically i have this code.But when i hit play the raycats are not hitting its object and idk if its bc i hvae the direction wrong or what.Heres code
void WalkRandomly()
{
TimeBtwnSteps -= Time.deltaTime;
if(TimeBtwnSteps <= 0)
{
float RandX = Random.Range(MinWalkValues.x, MaxWalkValues.x);
float RandZ = Random.Range(MinWalkValues.z, MaxWalkValues.z);
WalkPoint = new Vector3(transform.position.x + RandX, transform.position.y, transform.position.z + RandZ);
TimeBtwnSteps = Random.Range(0, 5);
}
if(TimeBtwnSteps > 0)
{
float XDir = WalkPoint.x - transform.position.x;
float ZDir = WalkPoint.z - transform.position.z;
if(Physics.Raycast(WalkPoint, WalkPoint - transform.position, out ObjHit,100f, LayerMask.GetMask("Worker")))
{
if(ObjHit.collider == this.gameObject)
{
Debug.Log("Valid Spot");
transform.position = Vector3.MoveTowards(transform.position, new Vector3(XDir, transform.position.y, ZDir), WalkSpeed * Time.deltaTime);
}
}
}```
Thanks for the insight, always been using the UGUI one π
heres ss they grey points are walk points
And if you drag the Text (DMG) now to your script, its not working?
Okay, so now can you drag that text into that box
well smth happened π
I can
When you drag a scene object (inside the prefab hierarchy) to your prefab and you are not in prefab mode, you need to save the override to your prefab. Or better, just go into the prefab mode and link it there to avoid this π
ok I can see it saying 9999 which is good now I need to work out the lookAt
wow THX SM.
@astral falcon can u plz take a look at my rpob really fast since your hear and experianced coder like you should be able to determine it in a sonics pace
plz?
π
THX for your help.
Pls no direct demand on people here. Most of the users just jump in and out randomly as I do and see, where they can help.
mb mb wont again sire
i dident ena to sound rude
All good, its just putting some pressure noone wants in freetime π
And for your issue, I suggest you look into debug.drawray or line and see where your raycast actually is firing to. Go from there
oh i just tried that
but i can get the right distance see
oh mybad
you said line
thank you
we got lines now
but how can we make that into a ray cast
so we can check if the point is blocked by an obstacle
i thoguht my raycast math was correct unless im worng
Doing anything to the capsule's or rigidbody's rotation re-introduces jitter. Just having Camera.main.transform.localRotation = Quaternion.Euler(rotX, rotY, 0); reduces jitter, but it doesn't entirely eliminate it. Super weird
Is there a way to reset the scene into its defalt view? For some reason, I am unable to move the scene view with my mouse
yes - they are in "Left" view though
I don't recall if that locks the scene camera though, i don't think it does
yeap, just reset the layout
yeah true maybe its locked
thats what i thought when i seen Left
but if that was ur last Iso view.. it sticks around
so, not enough of a clue
iirc if you hold right click you should still be able to rotat it no ?
I don't have unity open atm
ya, it goes back to perspective
so not sure.. his lock icon isnt locked.. and the 2D button isn't highlighted
so maybe a bug?
time to restart unity π
i've had situations where middle-mouse dragging doesn't work until I left click in the scene view to focus it
but I presume they're left-clicking with the hand tool here.
ive got into a habit of doing this every few hours.. just to keep the speed up
longer its open the longer it takes to recompile / draw
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
why am i getting the "Can't add script component 'movecam' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match." error even though my class name and file name are exactly the same?
well, do you haver any compile errors?
im not sure, how can i check
by looking at the console
well there you go
fix those
is your code editor highlighting these errors?
if not, it needs to be configured correctly
i think so
wait nvm i dont think it is
no... it is highlighting them
but i dont see anything wrong with them
π 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
as the errors say, you're missing a lot of semicolons
Also...
You need to pay closer attention when you copy things
you are simply copying incorrectly
hmm alright
Also remember C# is case sensitive
yeah i already had problems with that but i got them figured out im pretty sure
no you didn't
update is not the same as Update
the tutorial that i was following did it with a lowercase u for some reason
find a better tutorial
yeah that sound like a good idea
I suggest the unity tutorials from learn.unity.com . They are quite good to understand the basics about how unity is working
did u follow tutorials to learn unity?
alright ill take a look
thanks
No, I hate tutorials
then what did u do?
What every sensible person should do. I read the documentation and experimented a great deal
wait we should actually read the documentation???
Documentation > any tutorial out there
should have done thatπ
thanks
idk I never had to read libraries when I did coding
Well they sure as hell didnt write it for fun
If you want to learn anything to do with development documentation is the only thing you shouldf be reading
If you just rely on others peoples knowledge about something instead of the guys invented that something, you just adapt to their faults
I thought it was like for reference or if u needed something really specific
never thought it was something to actually sit down and read
thanks a bunch
everyone did watch tutorials. I even do it today to get the hang of like a new system introduced, but then still going over to the docs, see waht I can do with it. Test, play around and run into errors to understand the dos and donts.
Show it
I am very, very old school, when I was learning all there was to learn from was books
If you were able to get those at all π
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
I've read a UI unity book it's pretty basic
I guess it depends on the book
Which script was it?
playercam
yeah don't do delta time it's not needed
? What a suggestion π
Number of times it wasn't exactly like the tutorial: 153
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-3-28```
I was waiting for that
im 100% sure he used a small u one time, maybe it was another script or smth
Nope, just checked every script in the video. They're all properly capitalized
well then im tripping idk
maybe i just thought that it was lowercase since most is lowercase
idk
Every function they make in the video starts with a capital letter
Whatever, just pay more attention and do not rely on tutorials about how to write proper code
Best to know the syntax yourself so even if you end up as one of the unlucky 5 where the tutorial itself is wrong you know what to look out for
well idk how to start learning coding since it seems like there is unlimited stuff to learn
Check the pinned resources in this channel
Just start. Same suggestion as before. Go to unity learn platform and just learn the basic tutorials. You will get the hang of how unity works and from there you increase your skillset and that will open your abilitiy to try something new, add new knowledge and so on. You cant learn ONE coding thing to have it all. You learn how to use tools to achieve whatever your goal is.
There is, but if you learn the building blocks you can assemble them yourself, even if the tutorial leads you wrong
alright thank you all for your suggestions and help, i'll go figure stuff out nowπ
If... I want to do like a... stackeable effect? Let's say I want the player to gain X buff after killing an enemy for Y secs and I want it to be able to stack up to Z times. How do I do this? Through Coroutines? I would love to have control of if gaining a new stack does reset the duration for previous stacks or not with a bool if possible
Sounds like you could use a tick system or just seconds to reduce like a counter on every effect. It should not really matter, if you have an effect once or 10x if you just manage them with a constant tick. So you start the effect on tick 0, the next same effect on tick 2, and they all could last for 3 ticks, on tick 3 two would be active and on tick 4, only the second would run cause the first ran out. If you want them to reset any of the same kind, you could try to check for the same effect in your active effect list and reset all of the same kind if you set the "bool" of your effect to do so.
!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.
Even without a tick system, just running down every effect just by deltatime could have the same effect. have a start time, duration and check in your list
Hi all,
Sooooo, more maths issues. I'm trying to get a 'shield' system working, but having a bugger of a time figuring out my coroutine so that the shield effect fades
IEnumerator ShieldFade()
{
while(currentShieldVisibility > minShieldVisibility)
{
currentShieldVisibility -= Time.deltaTime * shieldFadeSpeed;
playerMaterial.SetFloat("_Shield_Visibility", currentShieldVisibility);
}
if(currentShieldVisibility < minShieldVisibility)
{
currentShieldVisibility = minShieldVisibility;
}
yield return null;
}
Any ideas where I'm going wrong please? (the shield 'coming on' is outside of the coroutine, this is just the 'fade out' part.
I guess, your shield just fades out to "0" immediately?
While loops run to completion. There's no yield in it so it's going to run until the condition is false
Yeah.
Yep, fixed it. Thank you π
Hi, I am having a problem with Unity's Random, every time I run my game it always produces the same results. Not sure whether I am misunderstanding how to use random. ```
[Range(0f, 1f)]
public float wormChance;
[Range(0f, 1f)]
public float zombieChance;
[Range(0f, 1f)]
public float spiderBeetleChance;
[Range(0f, 1f)]
public float crawlerChance;
[Range(0f, 1f)]
public float spiderChance;
private void Start()
{
InvokeRepeating(nameof(SpawnEnemy), 1f, spawnRate);
}
private void SpawnEnemy()
{
GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];
float random = Random.value;
if (random < wormChance)
{
enemyPrefab = wormPrefab;
Debug.Log("Worm");
}
else if (random < zombieChance)
{
enemyPrefab = zombiePrefab;
Debug.Log("Zombie");
}
else if (random < spiderBeetleChance)
{
enemyPrefab = spiderBeetlePrefab;
Debug.Log("SpiderBeetle");
}
else if (random < crawlerChance)
{
enemyPrefab = crawlerPrefab;
Debug.Log("Crawler");
}
else if (random < crawlerChance)
{
enemyPrefab = spiderPrefab;
Debug.Log("Spider");
}
Vector2 position = new Vector2();
position.x = Random.Range(spawnArea.bounds.min.x, spawnArea.bounds.max.x);
position.y = Random.Range(spawnArea.bounds.min.y, spawnArea.bounds.max.y);
Quaternion rotation = Quaternion.identity;
Instantiate(enemyPrefab, position, rotation);
}
}
!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.
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public float spawnRate;
public Collider2D spawnArea;
public GameObject[] enemyPrefabs;
public GameObject wormPrefab;
public GameObject zombiePrefab;
public GameObject spiderBeetlePrefab;
public GameObject crawlerPrefab;
public GameObject spiderPrefab;
[Range(0f, 1f)]
public float wormChance;
[Range(0f, 1f)]
public float zombieChance;
[Range(0f, 1f)]
public float spiderBeetleChance;
[Range(0f, 1f)]
public float crawlerChance;
[Range(0f, 1f)]
public float spiderChance;
private void Start()
{
InvokeRepeating(nameof(SpawnEnemy), 1f, spawnRate);
}
private void SpawnEnemy()
{
GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];
float random = Random.value;
if (random < wormChance)
{
enemyPrefab = wormPrefab;
Debug.Log("Worm");
}
else if (random < zombieChance)
{
enemyPrefab = zombiePrefab;
Debug.Log("Zombie");
}
else if (random < spiderBeetleChance)
{
enemyPrefab = spiderBeetlePrefab;
Debug.Log("SpiderBeetle");
}
else if (random < crawlerChance)
{
enemyPrefab = crawlerPrefab;
Debug.Log("Crawler");
}
else if (random < crawlerChance)
{
enemyPrefab = spiderPrefab;
Debug.Log("Spider");
}
Vector2 position = new Vector2();
position.x = Random.Range(spawnArea.bounds.min.x, spawnArea.bounds.max.x);
position.y = Random.Range(spawnArea.bounds.min.y, spawnArea.bounds.max.y);
Quaternion rotation = Quaternion.identity;
Instantiate(enemyPrefab, position, rotation);
}
}```
Better at least but this is definitely long enough to be in the "Large code blocks" territory
sorry, new to this lol
Is it spawning the same prefab every time, or is it spawning at the same area every time?
both
i can provide screenshot
it only spawns 2 of the 5 prefabs, and they are always in the same positions
the "crawler" always spawns at the top middle, and the "zombie" always spawns on the top right
none of the others ever spawn
Have you tried logging random and seeing if the number you roll ends up any different?
Is there a way to sense tiles through tags in unity? Trying to figure out how to do footsteps on 2D side scroller tiles
same number each time
What number is it?
0.91 and 0.44
they get logged alternately
I think 0.91 corresponds to the crawler and 0.44 to the zombie
you could try resetting the random.seed to get a new number
I wonder if Invoke might be somehow be like, running the code a single time and re-executing it each time, which means the random seeds are the same.
hey, do any of you guys know why my seeker from the a* pathfinding assets sometimes tries to pathfind through obstacles?
Generally, Invoke should be avoided for several reasons, and if it futzes with random that's another one
Try a coroutine instead
Start a coroutine that runs SpawnEnemy, then waits for spawnRate seconds, then starts another copy of itself
Ooh I wonder if this is The Bug
Sounds interesting
Is this a URP project by any chance
What is The Bugβ’οΈ
yes
Basically I want the footstep sounds to change when the player is on a different tile sprite. Idk how to implement it though
its going from blue to red? doenst look like its going through any obstacles
Some of URP's post-processing code calls Random.InitState and winds up giving you a completely predictable random state
It sounds like the bug has been fixed, though
What version of Unity are you using?
Wow, that's a pretty huge oversight
2022.3.18f1
raycast down
Check if you have an update for the URP package in your package manager. Should be fine in that unity version.
And seems like you were right about the invoke taking the same function when repeating, digiholic. It will not regenerate any random.seed and just take the seed it was started with
Dont think i have an update for it
Huh, that's also an annoying oversight. Why does Unity gotta keep mucking with the random seed! That's kind of an important thing to not mess with!

the random seed usually updates on every millisecond just by design, but if you like temporarily store that function in that invocation, you cant access the "new" seed. Not sure if thtas a bug or a feature π
What's the coroutine code look like?
same exact numbers?
yes
ye, show the code
{
StartCoroutine(nameof(SpawnEnemy));
}
private IEnumerator SpawnEnemy()
{
GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];
float random = Random.value;
Debug.Log(random);
if (random < wormChance)
{
enemyPrefab = wormPrefab;
Debug.Log("Worm");
}
else if (random < zombieChance)
{
enemyPrefab = zombiePrefab;
Debug.Log("Zombie");
}
else if (random < spiderBeetleChance)
{
enemyPrefab = spiderBeetlePrefab;
Debug.Log("SpiderBeetle");
}
else if (random < crawlerChance)
{
enemyPrefab = crawlerPrefab;
Debug.Log("Crawler");
}
else if (random < crawlerChance)
{
enemyPrefab = spiderPrefab;
Debug.Log("Spider");
}
Vector2 position = new Vector2();
position.x = Random.Range(spawnArea.bounds.min.x, spawnArea.bounds.max.x);
position.y = Random.Range(spawnArea.bounds.min.y, spawnArea.bounds.max.y);
Quaternion rotation = Quaternion.identity;
Instantiate(enemyPrefab, position, rotation);
yield return new WaitForSeconds(spawnRate);
StartCoroutine(nameof(SpawnEnemy));
}```
Unrelated but you don't need to use nameof for coroutines, you can just do StartCoroutine(SpawnEnemy())
I am not quite sure you are running into the same issue as with invocation here as you start it from within itself
should i use a seperate coroutine to call it then?
ok
so to make sure: you currently aren't mucking with Random.InitState, correct?
correct
you can try to set that initstate to a new value based on the current time for example
and you don't happen to be using splines?
i also found a bug with a specific spline component a while ago
that vanished from the Atlassian bug tracker page so I have no idea what happened to that report
dont know what a spline is lol]
how would i do that?
can you try Random.InitState(System.DateTime.Now.Millisecond);
should this go in the coroutine?
yep, just at the start
What's the exact version of the URP package you have installed?
this has helped somewhat
but it is still mroe predicatable than should be
14.0.10
It now looks like this
some enemies still spawn one the same position
and are the same type
eg in bottom left
two black enemies on same position
well, since you're seeding with the current time, that will happen if two or more enemies spawn at once
do you get the exact same number on those two?
yes
If multiple things start the coroutine at the same time, each "tick" of it will sync up between them
Since before, when the seed was fixed, you had two different numbers, I'm pretty sure you have two spawners
i only have one spawner in the scene
and enemies are only spawned one at a time, for each time the coroutine is run
I guess milliseconds is not the best to be used here, as every second could have the same millisecond returned if you run the spawnrate at a second span. Whats your spawnrate set to?
can you just get rid of milliseconds and use .Now?
thought so.
yeah, try to alter the spawnrate and also use .Now. that should get some more randomness in it
what is syntax for just now
just remove .milliseconds
after getting rid of milliseconds it doesnt like it
oh, whats the error?
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'System.DateTime' to 'int' Assembly-CSharp C:\Users\Mark\TopDownTest\Assets_Scripts\SpawningScripts\EnemySpawner.cs 38 Active
Try System.DateTime.Ticks
nope
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'long' to 'int' Assembly-CSharp C:\Users\Mark\TopDownTest\Assets_Scripts\SpawningScripts\EnemySpawner.cs 38 Active
nope
oh its long, right. hm, lets read the docs π
okay, I see that URP 14.0.9's changelog acknowledges the fix
Use local random state for post-processing.
cool
can you set (int) in front of that system.... ?
like how/
Random.InitState((int)System.DateTime.Now.Ticks);
thanks
Might fail too, just fiddeling around in discord right now π
Ticks is probably a huge value (one that surpasses the max value of int) so be aware that this will make it loop back around to negative values, or the cast will blatantly fail, not sure which
Yoooo no way I actually figured out how to use a raycast and tags to get it to play on certain sprites
all the logs are different
Nice, but be aware of what SPR2 said. It might fail at some point, but you get the hang of what to lookout for now π
It's way bigger than an int (638472563476759027) at the time I got its value, so yep it loops back to negatives, but doesn't throw a cast exception
So you're most likely safe in terms of getting duplicate values on different runs
note that this is pretty abnormal
we've bumped into another bug in a unity package or in some other code you're using
hey guys, just a real small thing here, im trying to get the name of the current scene. After some looking, I think im meant to be using Scene.name to get this, but Im getting literally no options for the Scene struct
I have declared "Using UnityEngine.SceneManagement" at the top of the script
I know yall hate screenshots but it best demonstrates what I mean here
is the start position minus the end position divided by 2 the midpoint?
if youre talking about vectors, yes adding two vectors and halfing the result is aleays the middle
thanks so much! now I just feel silly lol
the summary, not the subtraction.
(start - end) normalised will be the distance, divided by two will be the midpoint, yes
dont subtract it. You just get false results
If Jeremy is standing 1 metre away from you and Kevin is standing two metres away from you, adding together Jeremy and Kevin (1 +2) and halfing the result ((1 + 2)/2) will tell you that 1.5 metres is the middle of Jeremy and Kevin
Thats how i think about it
yep, good explanation
I would do a thorough read on mathematical vectors
Oh hell yeah, vectors are very sexy once youre invested in game dev
nah i know about vectors but im just horrid at maths so whenever i do a calculation and it doesn't work i cry
Quaternions: "Let me introduce myself."
dont feel bad for googling these things, all the math youll ever need has been done before and is usually explained somehwere obvious
I use Brilliant, the learning app, quite often
Yeah super cool
using bezier curves rn
and random is just made by a bunch of numbers stuck together
I made my own b spline script once in a agme engine that only had basic calculations
One of my proudest moments
inverse kinematics are sick
can someone just point me in the right direction?
i wanna make my own scroll rect
but a really simple one
which just uses scrolling
no dragging or scrollbars or anything else
Why make your own?
You can just delete those objects (sliders etc) and they are gone
Why reinvent the wheel?
im using OnDrag OnBeginDrag etc interfaces
for my inventory system
messes everything up
since scroll rect uses the same thing
trust me i tried everything
overriding the scroll rect OnBeginDrag etc
how do you think other games managed to pull it off?
probably made their own scroll rect
or didnt use OnDrag interfaces
and what will it listen to?
for inventory system
how you know if you drag the rect if not us ing ondrag or similar
"no dragging"
i just wannt use scrolling
on the mouse
to move content up and down
yo based af for explaining that, thanks. I just managed to get it working
my issue was half the problem, the other half was misunderstanding the bezier
No worries, happy to help π
Can you disable certain inouts when hovering over the scrolling thingy
you could disable the interaction of it but still get the mousewheel input to scroll the scrollrect
tried
Im not sure what youre trying to achieve but that seems like one solution
too complicated and breaks other things
Thast not so good
i just wanna make a simple script which moves content up or down
depending on scrollSensivity
and so it doesnt go above or below where it can
we dont have to get into the detail why
i tried everything trust
which would be the viewport
Well, sounds like you being kinda prejudiced about whats possible and whats not. Just cause you cant figure it out, doesnt mean, its not possible and more robust if you do it right with the builtin components. Can you explain exactly, what the user should be able to do with your scrolling inventory and the items in it?
you can use Clamp for that, but I don't think creating a custom scroll rect is the only solution. That's the last case scenario you want to be in, trust me
all i want is the player to be able to scrolldown this list
no dragging
no scrollbars
not anything excesive
Then its just some math you gotta do to get the size of the rect, the anchoredposition in relation to the screen and the overlapping so you know, what your min and max values are where you can lerp to with your mousewheel adding or subtracting
you got a mask image, thats your like 100% value. And the underlying content, which is your actual size to compare against. if its 120% for example, you can lerp between -20% on top or 0 to be at default position. kinda like that
yeah i get what u mean
it will still be a pain in the b to do that and make it feel smooth with all that inertia and easing I guess. but ye, that should do the trick
is it possible to only use the top half of a Random.insideUnitCircle?
check against the y position and see if its above?
i tried something similar and it didn't work
Get the random, then set the Y value to the absolute value of itself
If it's in the top half, it'll be unchanged. If it's in the bottom half, it'll mirror it to the top
im not sure what you mean by that
insideUnitCircle returns a Vector2. Store that.
you could also keep lerping to the clamped target position to get that nice bouncing at the end of the clamp values and make it kinda smoother
{
startPos = transform.position;
endPos = master.targetLock.position;
midPoint = (startPos + endPos) / 2;
randomDir = Random.insideUnitCircle * 12;
curvePoint = randomDir += midPoint;
}``` this is what im doing right now, how would i set the y value?
Set the y component's value to the absolute value of the y component
absolute returns the number without the negative
oh
Store the result of the random first, then abs the y, then multiply it
so i would abs randomDir after it gets random?
yeah i will
You basically use all random points of the circle but transform the lower half ones to be ones in the upper half with making y positive
Mathf.Abs(y)
oh right
How would you move a game object without explicitly changing its transform value? I need the object to still collide with colliders but it just passes right through them if I change the transform
CharacterController or Rigidbody
ok i think i got it, thanks guys
Moving a transform is like teleporting it and ignoring all physics checks
i have no idea how to clamp it tho
like the anchorpoints etc
anchoredPosition needs to be clamped to fit the mask overlap of your content. test around with values, you will get there
i always wondered how moving in a digital space wasn't always teleporting, considering you're constantly teleporting it in tiny increments to give the illusion of smooth movement. Are functions like moveTowards not considered teleporting because they do physics checks?
That sounds like meta thinking for a good wine talk in the evening π But basically yes, if you move the rigidbody or add force to it, it will consider physics checks before "teleporting" (as you might say) to the new possible position
It's not that you're moving in discrete intervals.
It's that you're leaving the physics system in the dark.
Hey, I'm learning the new input system. I'm trying to get an "OnKeyUp" thing going on butI can't sue the event "cancelled". It does print "OnDownwards" but not "DownwardsUp"
private void OnEnable()
{
playerInput.actions["Downwards"].performed += OnDownwards;
}
private void OnDisable()
{
playerInput.actions["Downwards"].performed -= OnDownwards;
}
public void OnDownwards(InputAction.CallbackContext context)
{
print("OnDownwards");
if (context.canceled)
{
print("DownwardsUP");
}
}
rigidbody.position = whatever;
This tells the rigidbody that it needs to move to that position in the next physics update
you will never received a canceled callback
you only subscribed to performed
ah i see.
I'll use that next, thank you
transform.position = whatever;
This will immediately move the transform. The rigidbody learns about this during the next physics update, and it just assumes that it was already in that position.
note that setting rigidbody.position is teleporting it -- it doesn't try to handle collisions between the original position and the new position
rigidbody.MovePosition(whatever) will ask it to move to the destination as if it just had a very high velocity
Wouldn't moving IRL also be considered teleporting since atoms are being moved at increments above planck length π΅βπ«
Also, if you have Interpolate enabled on the rigidbody, setting the transform's position might not even work at all
Interpolate causes it to set the transform's position every frame
It doesn't expect you to have messed with the position, so it just ignores whatever the current position is
i dont consider it that way. In real life everything has a measurable motion, no matter how tiny. But in the digital world, we can only measure speed down to a certain number of stored bits, so movement measured on a scale lower than that is teleporting. At least that's how i interpret it
Something to be discussed elsewhere I guess π
yeah, interesting topic though
i clamped the max up position
how can i clamp the lower one now?
calculate the maxScrollDownPosition i mean
You can only scroll up from the beginning, right? Like in terms of the rect, it can only go up when it sits on default
what do you mean
If you look at your rect of your content. you can only move it up from start, right? youcant move it down cause there is no content. so if you scroll it up by lets say 100px, you can also scroll it back down 100px, not further. Not sure you get what I mean
i put this targetPosition.y = Mathf.Max(targetPosition.y, maxScrollUpPosition);
just to show u
They're just making the point that in real life we can only measure down to the plank length, because movement in real life is quantized
i cant have the orange going higher than red
Than you have to check the difference of your mask height and your content height
yeah i get that. The way i see it though is that even if we can only measure down to planck length, its assumed there is a scale even lower than that. The same can't be said for digital.
Ah, that is incorrect. There is assumed to be NO scale lower than that. Real objects move at the planck scale. It is quantized, which is where the name for quantum physics comes from
@summer stump did you block me? π what did i do π
lmao
wait really?
Yes
there's nothing below planck?
According to our current understanding of quantum physics
something something 11-dimensional manifolds
STRING THEORIST! π
i actually got blocked, my life is over π
oh i see, i looked it up because i thought quarks were smaller than planck length but they're like way bigger
@swift crag sorry to budge in, but u know ui pretty well, how do i get the position of the red dot?
its using strech
I'm not that great at calculating that stuff via script. I should really figure it out already
RectTransform.rect is the shape of the RectTransform
You just get the preferredSize of it
(in its own local space)
this sounds like a LayoutElement thing
rect transforms do not have minimum or preferred sized
I am sure he will be using some grid layout element sooner or later. But ye, if its fixed, rect.height works too
I suppose you'd want to use Rect.NormalizedToPoint to get the local-space position of the bottom-center of the rect, then use transform.TransformPoint to turn that into a world-space position
you'd ask for the point at [0.5, 1]
world space position? For what? He just wants to get the local y position and the height to clamp the y position to its height within the viewport rect
ah, I interpreted "position" as being in world space by default
how can i make it so that when the player clicks, a thing happens, but when they hold, a different thing happens? Currently both things are happening even if they click or hold.
Are you using the new or old input system?
which is the old one
use a timer
is that really the most efficient way? I was really hoping there was something else i was overlooking
Are you using Input.GetKeyDown or something in your scripts or do you have an input asset for your actions?
input.getkeydown
Its just one way to do it, the simplest I could think of
Id say, learn the new input system right now. Best time to do so if you are not in a hurry with your project
is the new input system just that weird sphere with a thunderbolt in it as the icon?
because i've seen it before and i've heard how complicated it is
Wth? I dont know the icon of it π
Well, if you wanna stick to the old one, you might use a timer as navarone said
guess i will. I hate using timers so much, they're so messy
as well as code is with the old input system π
daily struggle
if(Input.GetKey(theKey))
{
timer += Time.deltaTime;
}else if (Input.GetKeyUp(theKey))
{
if(timer >= certainHeldThreshold)
{
//do held thing
}
else
{
//do clicky thing
}
timer = 0;
}```
something like this myba
alright downloading the new input system, it better blow my socks off
it's pretty neat
oh thats way less complicated than i was planning to make it
How do I reset the layout?
top right corner (Layout) button
Im using my right click but again, I am not too familiar with unity
Can you show me where it is?
its not hiding, its as top right as u can go w/o being on the close/maximize buttons
click it and go to Reset Layout.. that will reset all the windows
Okay. Thank you so much for the tip
Hey guys, a quick one, do playerPrefs get reset when reloading the scene they were set in?
If they dont then I got some bug finding to do lol
They don't, unless you explicitly do so via code
once u set the value, its there
Not resetting is kind of their entire job
// check and set player PB, change personal best text to reflect new records
if (PlayerPrefs.GetFloat(levelName + "PB") < finalTimerTime && raceEnd == true)
{
PlayerPrefs.SetFloat(levelName + "PB", finalTimerTime);
personalBestText.text = ("New Personal Best!");
}
else
{
personalBestText.text = ("Personal Best");
}
Im making an arcade racer
I want to store the personal best time between attempts and im reloading the scene for my "quick restart" function as im assuming thats the best way to do it.
So im comparing the previous PB to the current run finish time, then updating it ifs lower. thats the intent
Your PB condition looks backwards, it should save a timer that is lower than the saved one, not the inverse
Unless the longer you take, the better it is
No youre correct
Ill change it now
It was overwriting either way previously though, maybe that wont happen once changed
Yeah I just got a 5s time and it got overwritten by a 6s time
Ill do some investigating
begginer here. how can I stop the player from moving when touching something, it rotates forward or backward
2d
for example I make a coin and when i touch it I can make the player rotate
how would i create a circle of positions equal distance from each other along the edge?
is there a math function that lets me do that?
not sure if theres any built in functions for it, but its easy math.
r is the radius of the circle. take how many positions you want, lets say thats n. 360/n = how many degrees apart these should be in the circle
your angle will go from 0 to 360, increasing by 360/n. your formula is r * (cos(angle), sin(angle))
that math is in degrees, but you will need to use radians for mathf.sin
hi im making a pokemon game and all was going well but now my encoutner pokemon oes not work anymore
alright i'll give that a go
debug.log is free
Why do I access a GameObjects layer with gameObject.layer instead of this.layer?
"this" is used to reference the script
if it's inside of the same gameobject's script you can just use layer right it's part of GO not obj
ah, actually you do need to reference gameobject still
I thought that 'this' was used to target an instance of the object
but I think I understand what you guys are saying
instance of script vs instance of GameObject right?
this is useful for when you are inside of a method where you declared similar reference names, but 'this' keyword will always point the the current instance's member scope
it is, its just that "object" here means c# object. not a game object
thanks!
so gameObject will always target the instance of the GameObject the script is attached to?
!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.
is it not possible to start a coroutine from getComponent?
Just make a public method that starts the coroutine from within the class
oh yeah that works too
but how come coroutines dont start from getComponent?
am i doing it wrong?
Wdym they donβt start form GetComponent
GetComponent is a function, to get a component. you can then start a coroutine however you like
{
fb.GetComponent<FireballBehaviour>().HomingAttack(targetLock);
}``` doing this doesn't work for me
Thatβs not how you start coroutiens thatβs why
i get no errors but it also just doesn't work
Nothing to do with getcomponent
is your IDE configured? it should be telling you the fix for this, that is to use
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
i get no errors
Because there is no syntax error
look at the docs on fb it should be telling you something
void Update()
{
kretnja();
}
public void kretnja()
{
if (Input.GetKey(KeyCode.RightArrow) == true)
{
igrac.velocity = Vector2.right * speed;
}
if (Input.GetKey(KeyCode.LeftArrow) == true)
{
igrac.velocity = Vector2.left * speed;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true && Grounded)
{
igrac.velocity = Vector2.up * JumpStrength;
}
Youβre just not calling it with the startcoroutine
when i try to call it with startcoroutine it doesn't register my method name
it's technically not wrong to call a method that returns IEnumerator like that. it's just wrong if you want it to be a coroutine
Itβs more of a pain starting coroutine from another class
Just called the public method that will startCoroutine
I made the script for movement, however when I touch an upright block or anything similar, I can rotate the player while touching that block, I want my player to be upright at all times.
alright i'll just make a method for it
You need fb.getComponent<FireWhatevrr>().StartCoroutine(fb. getComponent<FireWhatevrr>() .HomingAttack())
or whatever
() is required unless you do it as a string (which you should not)
lock rotation in the rigidbody component
tried that already, doesnt fix it
Oh, you have to use dot notation from the reference, and still use the ()
Look at what nav said
Do GetComponent on its own line
one thing i dont understand
ive set the game objects
to their sprites
in the inspector
thanks!
i love context
hey yall, I'm having an issue with an animator controller where it's advancing through a clip despite not having a criteria to do so. could i get something to check it out?
the trainer sprite doesnt come up?
here's a short vid of my situation. I have a clip where something holds being hidden, one where it animates to being visible, another where it holds visible, and another where it disappears again. I have the two hold states set to have no exit time and only triggers for leaving the state. However, when I play back, it exits from disappeared anyway
also one thing, if I jump and hold left or right arrow to move to the side, I start gliding in the air and fall very slowly, how can I change that? I want to make my character be able to move in the air but for a very short time. I just want to limit the horizontal movement while in air. @swift elbow
add mass or add a gravity variable in your code
oh fixed it
If I add mass to the rigidbody 2d component nothing happens, it is still the same
add linear drag to stop it from gliding
may want to dampen the velocity towards 0 when not giving inputs
not sure.. can also turn up the gravity scale to fall faster
yes, but the thing is it stops falling as soon as I press right arrow to move right, I mean it falls but very very slowly
should fall the same speed if ur only giving it force in the right direction.. sounds like you might be adding forces elsewhere..
I'm guessing you're changing the Y velocity when you move from side to side.
Notably, if you set your velocity to Vector3.right * moveInput * moveSpeed, you're going to completely lose your Y velocity
Each physics update will move you down slightly because gravity accelerates you a tiny bit
public IEnumerator StunInPlace(float stunLength, float shake_strength)
{
stunlocked = true;
Vector2 originalPosition = armature.position;
float elapsedTime = 0.0f;
while (elapsedTime < stunLength)
{
float shakeStrength = Mathf.Lerp(shake_strength, 0f, elapsedTime / 1f);
Vector2 randomDirection = Random.insideUnitCircle * shakeStrength;
armature.position = originalPosition + randomDirection;
elapsedTime += Time.deltaTime;
yield return null;
}
armature.position = Vector2.zero;
stunlocked = false;
}
why isnt the armature transform moving?
is armature animated?
public class movement : MonoBehaviour
{
public Rigidbody2D igrac;
public float speed = 5;
public float JumpStrength = 5f;
public bool Grounded = true;
// Start is called before the first frame update
// Update is called once per frame
void Update()
{
kretnja();
}
public void kretnja()
{
if (Input.GetKey(KeyCode.RightArrow) == true)
{
igrac.velocity = Vector2.right * speed;
}
if (Input.GetKey(KeyCode.LeftArrow) == true)
{
igrac.velocity = Vector2.left * speed;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true && Grounded)
{
igrac.velocity = Vector2.up * JumpStrength;
}
armature itself shouldnt move, there are no keyframes for it
armature is the root object of the armature
this is my whole movement script
@swift crag scratch that it is animated LOL
that'll do it
and remember that the presence of any animation state having an animation clip that sets the position will mean the animator always writes to the position
even if you've never been to that state yet
zamn so i gotta go through all my animation clips to delete the position then?
You can also modify the position in LateUpdate.
You'd just add to the position every frame the shaking is happening
since the animator will be resetting the position every frame
how can i do late update with an enumerator though?
if(stunlocked){shake();}
honestly might just be easier to delete the positions in the animation clips, as they are never used and its always set to 0,0 anyways
hmm, the coroutine could just record values that you then use in LateUpdate
there's no convenient way to do that with coroutines
I've made my own "coroutines" before
so i dont think i'll be breaking anything
literally just making a list of IEnumerator and calling MoveNext on them all at the right moment
how can i have both of these and make the scrollbar work? this is what it looks like now
what is the enumerator class anyway?
the scrollbar updates, but i cant use it because i grayed out the OnScrollbarValueChanged
and if i dont gray it out, i cant move the scrollbar or scroll down with the mouse
only one of them works at the same time
Methods that return IEnumerator get some special treatment from the compiler
They get turned into a class that stores all of the information needed to remember where you are in the method
An IEnumerator represents something you can enumerate over
An IEnumerable is something that can give you an IEnumerator
(so you can enumerate over it many times)
IEnumerator is non-generic, so it just gives you a sequence of objects
(that's why you can yield return all kinds of stuff from a coroutine method)
IEnumerator<T> is the generic version, which provides a specific kind of object
and IEnumerable<T> is something that can give you an IEnumerator<T>
List<T> is a very common example of something that is IEnumerable<T>
foreach (var what in list) { Debug.Log(what); }
you could've also done
IEnumerator<int> enumerator = list.GetEnumerator();
while (enumerator.MoveNext()) {
Debug.Log(enumerator.Current);
}
Unity uses IEnumerators to implement coroutines.
i need like a bool to control if im currently using the scrollbar
You call a method that returns IEnumerator and pass the result to StartCoroutine
It then calls MoveNext() on your enumerator until it runs out of values
if the current value is something special, like an instance of WaitForSeconds, it can do different things
but if you discount that, then coroutines are pretty much just...
List<IEnumerator> coroutines;
void Update() {
coroutines.RemoveAll(coroutine => !coroutine.MoveNext());
}
public void StartCoroutine(IEnumerator coroutine) {
if (coroutine.MoveNext())
coroutines.Add(coroutine);
}
(unity immediately calls MoveNext on the enumerator you give it)
When you call an IEnumerator method, it does absolutely nothing
I used to think it ran until the first yield
it does not! but if you pass it to StartCoroutine, then it'll get MoveNext() called on it immediately
how can i detect if a scrollbar is being held
i tried placing an event trigger on the handle with OnPointerDown and OnPointerUp and calling a method which sets a bool either true or false
but having an event trigger component on the handle messes with the scrollbar and doesnt allow me to scroll at all
Howdy folks. I usually develop and debug with MS VS 2022. But since updating to 2022.3 my 2D projects are taking much longer to connect the debugger to, and hitting breakpoints takes 5-10 seconds where everything just freezes. Before I go scorched earth on this computer, does anyone have tips for how to get things working well again?
hey so how exactly would i have it so i call a function and i have it return a value so for example i want it when i attack a enemy it will trigger their damage function and if they die it will return a bool saying true that way i can store how many kills the player has
//example code
public bool TakeDamage(int damageAmount)
{
health -= damageAmount;
if (health <= 0)
{
Die();
return true;
}
return false;
}```
On top of that, I usually do an out with a struct of data including name of the enemy killed and perhaps points it gives. That way I can have a kill list for each unit. That can just be fun for strategy games when some super low level unit steals the kill on a heavy high level unit. Like "tf, that worker killed a tank?!"
ya, not knowing his setup i did bare basics.. id probably have a manager where i pass in the enemy and return his health maybe.. but my enemy scripts usually take care of their own stuff if they die.. they would tell a gamemanager about it instead of my attack knowing bout it
I have the following HLSL code for a custom function in shader graph, which works perfectly fine (basically just the sample texture 2D node at the moment)
#ifndef BIOMES
#define BIOMES
void Biomes_float(UnityTexture2D Tex, UnitySamplerState SS, float2 UV, out float4 Out) {
Out = SAMPLE_TEXTURE2D(Tex, SS, UV);
}
#endif
however, UnityTexture2D and UnitySamplerState are not defined types, so my code editor is complaining
Cannot resolve type: 'UnityTexture2D'
is this not a beginner question?
it's a shader question
I understand that it's for a shader, but my question is about how to resolve the type error. I'll repost the question regardless
To be clear, shader programming is different to general coding in Unity, which is why it's not really suited to this channel
Does OnTriggerEnter work with character controller?
thats why im asking bro @slender nymph
I tried it
well if you tried it then you should have seen that it does, in fact, work
No it does not
then you've set something up incorrectly
see, my player is controlled charactercontroller, im trying to make a checkpoint system and attached a checkpoint script to the checkpoint object with isTrigger turned
does your player have a collider?
Yes
the CC is a collider
and is also what will produce the OnTriggerEnter message
what have you actually done to check whether OnTriggerEnter is being called
show your code
ok
and both objects involved in the trigger overlap
!code ```public class Checkpoint : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("Checkpoint set");
GameManager.Instance.SetCheckpoint(transform.position);
}
}
}
@slender nymph
well for starters, you aren't actually confirming that OnTriggerEnter is being called with that log. and you should also be using the CompareTag method rather than string equality to check tags
hey been messing around with fmod and im trying to play a sound for every time the player selects a slot
realized after implementing a debug.log that the sound constantly plays cause its in the void update
ive tried a few thing but at this point i need some advice https://hastebin.com/share/ipugagejom.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
instead of manually checking for a selected object, you could instead implement the ISelectHandler interface on some component on those selectable objects and just play the sound when an object is selected
just play it when you select a new object
That's the better way ^
A simple if statement here would have worked too:
if (selectedGameObject != null && _selected != selectedGameObject) {
_selected = selectedGameObject;
// play sound here
}
Hi, I'm currently trying to create an inventory system, but I'm encountering a problem. When I try to initialise the inventory, the boxes for the items instantiate but their parent is not defined because "the definition of the parent of a transformation that resides in a Prefab Asset is disabled to avoid data corruption" and I don't understand why I can't define this parent.
ItemUi (boxes for the items) might being instantiate in the panel "Items"
Can someone help me ? I added some pictures and a few code snippets
if your contentPanel variable in UI_InventoryPage refers to a prefab that won't work, you need to assign a scene object as the parent
Content panel is part of a prefab. I already tried to assign a empty gameObject as the parent but it didn't work, I had the same console error
Content panel is part of a prefab.
well there's the issue. it must be an object in the scene. is it perhaps part of the same object that your UI_InventoryPage component is part of?
your code doesn't make sense then. Why would you try to instantiate an object as the child of a prefab?
Also, Instantiate allows the parent to be passed in directly to the Instantiate call. Setting the parent during instantiation is the best way for UI elements to get proper layout.
Hey guys! Im trying to have my enemies respawn if the player has to respawn as well and having a bit of trouble. Heres a few screenshots of the code im using. Any help will be much appreciated!
- Don't share code with screenshots
- Explain what trouble you're having specifically
!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.
Content panel is part of "inventory" prefab, which contain UI_InventoryPage script.
I actually don't know that I can do that. How is it possible ?
okay and does the InventoryController object have a reference to that UI_InventoryPage prefab, or does it reference the one in the scene? if the former, that's the problem
Read the docs for Instantiate.
Instantiate(prefab, position, rotation, parent)
Ok here's your actual problem
You are calling InitializeInventoryUi on your prefab reference
you need to actually instantiate the prefab, then call InitializeInventoryUI on the instance
alternatively, if InventoryController is supposed to reference the copy already in the scene, it needs to actually refernece that copy, not the prefab itself
Sorry about that! Well i have it so when the player dies, the game fades to black and the player respawns at a checkpoint. However any enemies that were defeated before the death stay defeated, and im trying to find a way to have them respawn as well. Ive tried giving them the player tag and creating a new enemy tag to get them to respawn but to no avail.
Either:
- Simply reload the whole scene
- Keep a list of the enemies that died. Respawn all the enemies in this list when respawning the player
Okay, I'll try that when I get home. Thanks !
How would i go about making a list for the enemies?
List<WhateverYourEnemyScriptIsCalled> or List<GameObject>
Oh okay! And then how would i make them respawn? Thats where ive been having a bit of a problem
that depends on what "respawn" means for you
presumably just set them active and set their positions back to their spawn positions
basically - reset everything that needs to be reset.
Oh gotcha. Ill give that a try along with the list. Thanks!
Hey yall, I'm working on a movement system for my first VR game in unity. It's physics based for a number of reasons, and I need to use the AddForce method on the player rigidbody to get the movement I want.
So far I've got pretty much everything settled until I add more features, but there's this one problem that's been bugging me.
When the player is on the ground, a high velocity naturally slows due to friction, but in the air its velocity is almost unchanging. I want players to have a small amount of control in the air to help them land where they want, but I also don't want them to speed up their horizontal movement too much while falling. The code I ended up with to try and solve this would theoretically allow the player to use the joystick on their controller to increase or slow their movement if below a certain speed, and only slow their movement, but not increase it if above that speed.
Of course, I wouldn't be here if it worked so I'd appreciate some advice on what I need to change to allow it to work correctly.
{
Body.AddForce(newForce, ForceMode.Acceleration);
}```
CurrentSpeed and XZSpeed are Vector2's, and XZSpeed is the x and z components of the newForce Vector3
intuitively:
- Get the max of the current velocity magnitude and the speed the player can manually accelerate themselves to
- Add the input force to the player, as an impulse (or directly combine with the velocity)
- Clamp the new velocity by [1]
You need to account for direction
how so?
yeah, it would fall within the clamp if so
Basically you will need to use vector projections
You can't do 3.
if you do 3. then external forces can't accelerate you past the max velocity either
though I guess it's not clear if that's a requirement or not.
yes the max velocity isn't a hard limit
it's a limit to the player increasing it further
yeah. I actually have an asset in progress to do exactly this, it's not quite ready yet though.
i had a method previously that did that but it would slow the player down if you attempted to move forward past the max velocity which isn't ideal
the math is actually quite annoying
dang, i thought itd be simpler lol
can anyone explain why (CurrentSpeed + XZSpeed).magnitude < CurrentSpeed.magnitude
doesn't work though?
im fairly new to vector math stuff lol
well it's unclear what those things are
this is why you do #1 - if the player is already moving at a high speed, moving in that direction wont reduce it
Current speed is the horizontal velocity vector of the rigidbody
XZSpeed is the horizontal vector of newForce
newForce is movement direction (obtained from the analog stick and the look direction) * the sprint force
well for one, simply adding XZSpeed is not the same as Body.AddForce(newForce, ForceMode.Acceleration);
it would have to be + XZSpeed * Time.fixedDeltaTime
they would be equivalent if you use ForceMode.VelocityChange
wait that makes so much sense, it would only be equivalent if i used foremode velocity change
yeah
well let me test that rq deynai's method didn't work tho i prob did it wrong
yeah that worked perfectly actually, i cant increase my forward velocity past a certain point but can slow down midair
thanks for the help yall
transform.position.x += 5;
why is this not allowed
because transform.position returns a copy of the position data
so modifying the x on the copy would do nothing
rather than do nothing and make you frustrated, it gives you an error
You can do transform.position += Vector3.right * 5; for the same effect
or transform.position += new Vector3(5, 0, 0);
then why is transform.position += allowed
if it returns a copy, how does that mutate anything?
because this is setting the position as a whole
this is what position looks like in Transform:
public Vector3 position {
get {
return _internalPosition;
}
set {
_internalPosition = value;
}
}```
transform.position += is calling the SETTER.
transfrom.position.x is calling the GETTER
i wonder why Unity cannot kinda convert it automatically, so when you do
transform.position.x += 5;
unity will automatically convert it to
transform.position += new Vector3(5,0,0)
it has nothing to do with Unity
it's C#
no
Unity uses C# largely unmodified
it can't change the rules of the C# language
i see
What they can do is stuff like they did recently with Rigidbody2D
can you make some extension methods though?
to easily modify just the x for example?
transform.position.SetX(5)?
i dont understand the rationale though..?
Yes you can do something like that
this still wouldn't work because the Vector3 returned by transform.position is a copy of the vector
I use something like that in my code often
are they just trying to force some opinion about how to do OOP on me by making x only gettable and not settable
they would have to make transform.positionX as a property
so it would have to be actually
transform.position = transform.position.SetX(5);?
so im even more confused now, since velocity is also vector3
can't they make the same for transform.positionX?
velocityX would be a float property
yes they can make this. They haven't yet
alright i get it now
As for extensions you could use an extension like I have here:
https://github.com/jschiff/unity-extensions/blob/338d306ba17f86efa7beea1618ef486132e42720/Runtime/Extensions/VectorExtensions.cs#L19
Then you could write transform.position = transform.position.WithX(5);
so basically when modifying the velocityX, the setter of that property is changing the actual velocity vector?
just an annoying conceptual hurdle for my students. transform.position.x += 5 would be significantly easier for them to understand.
transform.SetX(5); if you must
yes it would look something like:
public float velocityX {
set {
Vector2 vel = this.velocity;
vel.x = value;
this.velocity = vel;
}
}```
i'll add that to my collection, so far i only have EnumerableExtensions with stuff like GetRandom() or Shuffle()
especially the GetRandom() is used very often by me
instead of doing the Random.Range(0, arrayLength)
You could also look at it as a gentle hurdle to begin understanding the ideas of reference vs value types
hi how can i make a raycast for instanciate a object at the end of the raycast i want the ray as made by the position of my mouse
which is line 117 of CraftingSystem.cs
so nothing is assigned on axereq1?
correct
Text is not the same as a TMP_Text component
that text is completely different
then show that object and the Text component on it
oh it has textmeshpro
theres also a couple more problems im facing like earlier if i pressed C my inventory was opening but now nothin happens is it cus of this error? that my inventory is no longer opening
exceptions will stop the execution of the method they happen in so anything later than your error would not have executed
also you should consider using a better way to get a reference to those TMP_Text objects instead of chaining transform.Find calls
oke
i hope it works now
cus im getting like 4 problems i hope its cus of this
make sure you are also addressing your errors starting with the earliest in the console and not just the latest. typically the earlier ones are the cause of the later ones
im still facing 1 problem but i can fix it ik why it is caused
ohh ok ill keep this in mind
Hey guys, been stuck on this for too long... Doing my first unity project for a uni assignment and I can't figure out why my ball is constantly spinning in the z axis when it makes a collision, not sure if im missing something?
It has a regular sphere collider, default rigidbody, and a character controller. I have a camera following it with cinemachine but isn't related as bug still persists when disabled fully
This is the script for movement + the small part I have added for collisions which will be used for jumping, im completely lost? anyone have any idea what could be causing it?
!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.
void Update()
{
Movement();
//Jumping();
}
//double jump prevention
private void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision!");
Debug.Log(collision.gameObject.name);
if (collision.gameObject.tag == "Ground")
{
isOnGround = true;
Debug.Log("isonground true");
}
}
void Movement()
{
float Horizontal = Input.GetAxis("Horizontal");
float Vertical = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(Horizontal, 0.0f, Vertical);
float magnitude = movementDirection.magnitude;
movementDirection = Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * movementDirection; //movement adjustment based on camera
movementDirection.Normalize(); //diagonal control - stops diagnonal being way faster
controller.SimpleMove(speed * movementDirection * magnitude); //character controller movement
}
why don't u try .AddForce methode to move the ball?
why is it terrible?
Doesn't seem that there is anything in the controller that would do that, what does it do when you dissabled the script?
It's slow, it's fragile because it relies on you setting the name correctly in inspector and in script, and then relies on you never changing the names. One accidental change to 1 string or you accidentally name something the same as the object you're trying to find and the game breaks
I did that originally but then when I added in the use of cinemachine i ended up changing it all around, I could give that another go though
Anyone can help me with this? I can play the game with the Unity "Play Button" but I can't build it
if i disable the script it doesn't do the rotating, which is why Im puzzled as I cant see anything in there causing it
The error tells what's wrong. You can't use editor API in a build.
but why
Because you don't want your users to download a whole editor to play the gameπ€¨
and how do I fix it
Don't use editor API in the build.
If it's only needed for editing time, wrap it in a preprocessor define.
how do I remove editor api in the build?
The message above
"wrap it in a preprocessor define."
Im new to this and I don't know what that means
Mmmm... Probably there is something wrong in the controller itself? Cause I don't think any of that should cause rotation. Try just locking the rotation as last resource
Can read more about it here:
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
havent used character controller before but pretty sure its all default atm?
Problem is its for a marble game so I need the ball to be able to rotate
I understand nothing
Time to learn thenπͺ
Surely you understand at least something. It's mostly English.
can you just tell me what to delete for it to work?
The error tells you
So you know how to read errors?
I see this "Assets\LogicScript.cs(5,19): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)"
pobably I can't
im getting this error "Assets\Scripts\InputManager.cs(23,15): error CS1061: 'PlayerMotor' does not contain a definition for 'ProcessMove' and no accessible extension method 'ProcessMove' accepting a first argument of type 'PlayerMotor' could be found (are you missing a using directive or an assembly reference?)
" and idk whats wrong i have been searching for like 30 min now. Here's the scripts
The important part is path to the script and line number of the error. Do you understand what it is?
hmm, Assets\LogicScript.cs("Somewhere in grid (5,19)?")
idk
Break it down. What's the name of the script?
Good. The numbers following it are line number and character number in the file.
Yes. Does it say anything about editor?
ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
but how do I remove it without braking the code?
Change your code.
There's no way to use editor API in the build. It's like asking "how do I break laws of physics"?
The answer is don't break them in the first place.
Any shorter way to write this ?
n==2 || n==7 || n==x
Whatever you're doing there, you probably don't need the editor API there.
Put the values in an array, loop and check again each element.
EditorSceneManager. How did you come to using it in the first place?π
SceneManager didnt exist
I'm sure there's no single tutorial that suggests using it.
Probably because you're missing a namespace.π€·ββοΈ
But you decided to use a namespace that you shouldn't use instead.
so how do I replace / fix it?
Well now its gonna be a few lines.
One to init the array, one for the for loop, and one for doing whateer operation i wanted to do if these conditions are true:
int[] nums = [2,7,x]
for(int i=0; i<nums.length; i++)
if(n == nums[i]) //operation
Well, start from understanding what you're trying to do
π΄ Get bonus content by supporting Game Makerβs Toolkit - https://gamemakerstoolkit.com/support/ π΄
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
Thats even longer then
if(n==2 || n==7 || n==x) //op
I assumed that you have more than 3 conditions. If it's just three, the previous way is probably the best.
Is there a way to detect spikes in a music track? like if DB >= 90 ??
Not unless you use some low level API I think.
When i clitched this button. I got this error.idk how i fix it tho ik what it means.
AxeCraftButton is null.
You should be using Debug.Log to find this sort of thing
wait the button is null?
yes, read the code it cannot be anything else
oh ok let me check
this is why i should have never used find to get the button
its so hard to find the error
indeed also why you should try to understand every line of code you write and not use copy/paste for code you do not
i never copy paste code even if im provided the code i first watch the whole video and then try to write it again myself
i cant copu it either if i want to cus the game they are making in the video and the game im making are similar but not the same
i did find the problem
i gave the wrong path while using find
what does this mean
looks like infinite recursion
Just a tip, you could use a property to access the inventory system easier.
public InventorySystem InventorySystem { get { return InventorySystem.Instance; }};
Then you just call this.InventorySystem rather than InventorySystem.Instance.
There's even an easier way to write this:
public InventorySystem InventorySystem => InventorySystem.Instance;
ohh
thx
You added code that caused a stack overflow, and this usually means recursive code that never ended in the same frame, or you simply put too much work in the current frame. Share what you added that caused this.
im getting this error "Assets\Scripts\InputManager.cs(23,15): error CS1061: 'PlayerMotor' does not contain a definition for 'ProcessMove' and no accessible extension method 'ProcessMove' accepting a first argument of type 'PlayerMotor' could be found (are you missing a using directive or an assembly reference?)
" and idk whats wrong i have been searching for like 30 min now. Here's the scriptsv
im still getting the same error.The axe blueprint isnt supposed to be none
post the !code for onFoot
π 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 think i got it
its done in input actions
if this works i dont know any reason why it wasnt working before but
post the PlayerInput code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is someone able to guide me on how to use the Player Input Manager correctly?
I can spawn my player prefab correctly when 2 controllers are attached, but want to make sure these are correctly identified as Player 1 and Player 2 to be able to use this reference for the scoring later on
irgnore me, worked it out π
Can I subscribe as many methods I want to a single event? In the same class?
I mean player class subscribes 3 of its methods to an event
I don't know of any maximum
3 is nothing, yes you can
all right thanks a lot.
Guys, any idea on why this is spawning all the cubes on the same spot? https://hatebin.com/qqamrnlrml
Try logging SpawnPosition. See if the issue is that the random is getting the same value, or if something is overwriting the object's position after spawning
https://gyazo.com/0e2ddfe0cfd0ebac634ef397aaf651a1 looks like random is working, probably something is overwriting the object's position
So check SpawnFromPool to see if you're properly using that position, and check any scripts on the spawned objects to see if they move themselves
it's weird, objectpooler looks fine too tbh
idk what's causing that, now i'm getting a nullreferenceException after i restarted unity
Probaby best to share ObjectPooler.
I'm not sure what chat would be appropriate for this but I'm getting this error and I have no idea what could be causing it, I already tried deleting literaly every object in my scene and it still shows up
does anyone know what could be causing this?
the first two are editor bugs
as for the rest - looking at the full stack trace may shed some light
https://hatebin.com/zathakpliv don't mind the comments, i was learning how objectPooling worked. @static bay
https://gyazo.com/b72d1eab286e7ca5411c60fc2eb39755 this is the nullreference i'm getting
oh alright thanks apparently the other 4 were also bugs, restarted it and seems to be fine now
I made a game that consists of randomly generating dungeons through corridors, having a playerroom (room where the player spawns) and fightpitroom (room where there are enemies to defeat) and I would like to add something to the game so that the playerroom room, the items do not change location, how can i do that?
well things don't just "change location" on their own. What are you doing that makes them change their location?
i create a procedural dungeon generator
Seems like ChatGPT comments.
yes you said that already
Are you asking how to generate the same dungeon multiple times?
no, im asking how to dont change the place of the itens on the playerroom
Actually, never mind.
It's not lol, chat gpt doesn't say "We wanna disable it at the start etc", it never uses we etc
what is "the playerroom"? And what causes items to change places?
as far as i know
to be exacly equal when i generate the rooms
Ya sorry I've seen so many of these the past week. GPT likes putting comments for nearly every line of code.
Mb.
yeye ik but that's just me wanting to understand every line of code
this is the playerroom that have the player object and the prefab placer that have the prefab to the itens spawned on the dungeon
I don't really know what this screenshot is supposed to tell me. I don't know how your game works. All I can say if you want the player room in the same place is, write your code to put it in the same place.
As for items I have no idea how items work in your game
but where can i change that code do put in the same place ?
how would i set the transform euler x to zero? ```
transform.rotation = target.rotation;
transform.rotation *= Quaternion.Euler(-90f, 0, 180f);
//transform.rotation.Euler.x = 0; //sudocode
//transform.rotation *= Quaternion.Euler(0f, 1f, 1f); //sudocode
//transform.rotation.x.normalize(0); //sudocode
the playerroom code its a part of a system responsible for generating rooms in a game environment, placing items and enemies within those rooms, and spawning a player at the center of each generated room.
and the prefab placer provides functionality to place items and enemies within the game environment, handling instantiation both during gameplay and in the Unity editor environment.
hi im new to unity and i am whenever i upload a decent photo for my 2d game it looks horrendus ingame, i have disabled the filters and messed around with import settings and cant figure out why? other games dont have this issue so there has to be a solution but i cant find it
@queen adder share a screenshot of what's happening
heres the photo side by side, the ingame is the best i could get it to look after 1 hour of tweaking random settings i have no idea what do lol
both same image just one is lower quality
can you take a screen of the settings?
import?
ye
that's not pixel art, you can try trilinear or bilinear i think.
on the filter move if you haven't already tried
yeah unfortunately this does not do much to help, i think its something to do with aliasing idk tho
have you tried with different images?