#๐ปโcode-beginner
1 messages ยท Page 497 of 1
if u want to teleport ur character controller ur gonna need to do a work-around..
disable it first.. then move it then re-enable it
Silly question, but how can I reference the charactercontroller from the assigned GameObject for "thePlayer"?
(Try)GetComponent
GetComponent if u have the object
Yeah, the object is under something else I already tried that
u have the player gameobject..
or since you are serializing a reference to the object already, just reference that component directly instead of referencing its gameobject
player.GetComponent<CharacterController>();
tf is even that?
there are beginner c# courses pinned in this channel. start there instead of randomly guessing
the assigned object
myController = thePlayer.GetComponent<CharacterController>();```
or what box was saying was just use the CharacterController..
public Transform teleportTarget;
public CharacterController thePlayer;
Thanks, this helped
yup, its always better to assign things by the Type ur wanting to use
instead of using GameObject.. b/c then ur gonna just have to grab all the components off of that gameobject anyway
if u have a component directly.. its always easy as theComponent.gameObject; <- to get the actual gameobject
Guys how would I get exact position of this stick? I think with script im getting like world cordinants
CachedXPos.Clear();
foreach (var stick in StickUIs)
{
CachedXPos.Add(stick.transform.position.x.);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
Debug.Log($"stick.{i} - {CachedXPos[i]}");
}
Good to know, that's what was confusing me
I can reference directly off of it with the main controller
thank you
localPosition.x
I see
world coordinates are the exact position tho..
don't need it
I think I can still do it without raycast xd
Coz raycast confuses me a lot...
gonna do it hard code way xdd
u could always save the positions uve spawned things at before..
thats what im doing
and then loop thru that collection.. when spawning a new one
sounds good to me
trying to do I guess...
gotta try first ๐
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
foreach (var stick in StickUIs)
{
//x - 9
//x2 - 0
while (randomXPos >= stick.transform.localPosition.x - 10f || randomXPos <= stick.transform.localPosition.x + 10f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
foreach (var x in CachedXPos)
{
if (randomXPos >= x - 10f || randomXPos <= x + 10f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
}
else
{
break;
}
}
if (randomXPos <= stick.transform.localPosition.x - 10f || randomXPos >= stick.transform.localPosition.x + 10f)
{
Debug.Log("Stick Should've spawned at right place.");
break;
}
}
}```
Look at this code mosntracity
So, here's an issue I have
I'm trying to implement a "lock on" system, where, whenever you press Q, your character starts always facing the current enemy
The issue: the way I handle diagonal strafing without lock-on is by using offsetting the direction the character is facing to make it go diagonally. This is fine in itself, but I don't know how to implement the same thing in the lock-on mode, and all attempts have gone pretty bad so far.
thats tame compared to some of the stuff posted here daily
wym tame
offset.z = walking? 1f : 0f;
offset.y = 1f;
if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
} else offset.x = 0;
cameraDirection = cameraTransform.rotation * offset;
cameraDirection.y = 0;
if(lockedOn){
Quaternion targetRotation = Quaternion.LookRotation(enemy.transform.position - transform.position - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f));
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime));
} else if(!lockedOn && cameraDirection != Vector3.zero && !animator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) //if the direction is valid and the player isn't attacking
{
Quaternion targetRotation = Quaternion.LookRotation(cameraDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning
}```
(edit for clarity)
sounds to me its gnna be pretty complicated code for anyone but you to fully understand lol.. you can share the code.. and ๐ hope that someone can help lol
okay let me simplify it a bit then
private List<float> CachedXPos = new List<float>();
private Vector3 SpawnPos;
float minX = StickSpawn.position.x - 9f;
float maxX = StickSpawn.position.x + 9f;
float minY = StickSpawn.position.y - 1f;
float maxY = StickSpawn.position.y + 1f;
float randomXPos = UnityEngine.Random.Range(minX, maxX);
float randomYPos = UnityEngine.Random.Range(minY, maxY);
if (StickUIs.Count == 0)
{
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
CachedXPos.Add(SpawnPos.x);
}
else
{
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
foreach (var stick in StickUIs)
{
while (randomXPos >= stick.transform.localPosition.x - 10f || randomXPos <= stick.transform.localPosition.x + 10f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
foreach (var x in CachedXPos)
{
if (randomXPos >= x - 10f || randomXPos <= x + 10f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
}
else
{
break;
}
}
if (randomXPos <= stick.transform.localPosition.x - 10f || randomXPos >= stick.transform.localPosition.x + 10f)
{
break;
}
}
}
}
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
Debug.Log("Stick Should've spawned at right place.");
CachedXPos.Clear();
foreach (var stick in StickUIs)
{
CachedXPos.Add(stick.transform.localPosition.x);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
Debug.Log($"stick.{i} - {CachedXPos[i]}");
}```
Still not working...
Sticks should spawn atleast with distance of 10 on X axis :(
if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
} else offset.x = 0;
offset.y = 1f;
offset.z = walking? 1f : 0f;
cameraDirection = cameraTransform.rotation * offset;
cameraDirection.y = 0;
if(lockedOn){
Vector3 enemyDirection = enemy.transform.position - transform.position;
Vector3 enemyDirectionMinusY = enemyDirection - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f);
targetRotation = Quaternion.LookRotation(enemyDirectionMinusY);
} else if(cameraDirection != Vector3.zero)
targetRotation = Quaternion.LookRotation(cameraDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning```
@rocky canyon should be way better
How do i add gameobjects to a list by name at start? I have 30 different objects, that i need to put into a list, but doing it via the editor would take ages.
maybe using tags?
you could use tags
all good answers
for each gameobject with a specific tag, add it to a list
basically just convert that into code
I was trying to avoid adding tags because it would only be used once, but i'll just do it.
Do they all have the same script component?
They are all just empty objects.
why not instantiate them then
They all have specific positions and rotations.
Could also put them under the same parent, and on the parent have a script that loops through its children
Yes, but how? I was thinking about this.
also why is it that
Quaternion x;
is not equal to Quaternion.Euler(x * Vector.one);?
What is Quaternion x supposed to be?
You mean someQuaternion.x?
basically any quaternion
x is just an arbitrary variable name
Because default Quaternion isn't even a valid rotation.
Also maybe you mean euler zeros
nono, I mean
let's say that x is the rotation of an object
which is already determined
Because a Quaternion is not a set of euler angles no matter how much you want it to be.
Any ideas on this guys?
And a direction vector is not the same as a set of euler angles either
Maybe you're looking for Quaternion.LookRotation?
well then how could I multiply a Quaternion with a vector3 without getting conversion errors?
I doubt it? I'm trying to basically turn the player by like 30 degrees
You don't get any conversion errors when doing so
Please show an example of what you mean
You would multiply a quaternion of said 30 degree rotation with the player's current rotation
No Vector3 needs to be involved at all
Because that isnt even related to converting. Multiplying is rotating the vector
perhaps I am approaching the issue wrong
nono, I'm trying to rotate the player by 30 degrees
That is what I was explaining how to do
player.rotation *= Quaternion.Euler(0, 30, 0);``` for example
Assuming you mean y axis
Basically, I want to make it so whenever the player is strafing, it uses enemyDirection = enemy.transform.position - transform.position; in a Quaternion.LookRotation
so it just looks towards the enemy
Ok what's the problem?
but when I'm strafing diagonally, I want to give it an offset
Sharing your actual code etc would go a long way to a solution
so you can either approach or distance yourself from the enemy by pressing W/S
I did up there, lemme resend
if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
} else offset.x = 0;
offset.y = 1f;
offset.z = walking? 1f : 0f;
cameraDirection = cameraTransform.rotation * offset;
cameraDirection.y = 0;
if(lockedOn){
Vector3 enemyDirection = enemy.transform.position - transform.position;
Vector3 enemyDirectionMinusY = enemyDirection - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f);
targetRotation = Quaternion.LookRotation(enemyDirectionMinusY);
} else if(cameraDirection != Vector3.zero)
targetRotation = Quaternion.LookRotation(cameraDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning```
Anyway there's no offset in this code
At least not when the enemy stuff is happening?
cameraDirection = cameraTransform.rotation * offset
in the enemy stuff I removed it because it was faulty
but I wanted the same thing that I had in the non-enemy stuff
It's not clear what offset is or what cameraDirection is
cameraDirection is the direction the camera is facing
that way, whenever I press W, the character moves forward relative to where forward is from the camera
I mean that I don't even know what data type they are or where the data came from
//generating random position
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
foreach (var stick in StickUIs)
{
//checking if position is compatebale with other sticks.
while (randomXPos >= stick.transform.localPosition.x - 5f || randomXPos <= stick.transform.localPosition.x + 5f)
{
//if not change position
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
foreach (var x in CachedXPos)
{
//check if its alright with any other alreadySpawnedStick x positions
if (randomXPos >= x - 5f || randomXPos <= x + 5f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
}
}
//if its far enough.
if (randomXPos <= stick.transform.localPosition.x - 5f || randomXPos >= stick.transform.localPosition.x + 5f)
{
break;
}
}
}```
```c#
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
//Debug.Log("Stick Should've spawned at right place.");
CachedXPos.Clear();
foreach (var stick in StickUIs)
{
CachedXPos.Add(stick.transform.localPosition.x);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
Debug.Log($"stick.{i} - {CachedXPos[i]}");
}```
Couldn't get it working...
any ideas?
but yes, this worked
thank you very much!
You should ask your question again instead of making people scroll
Or at least link to the original question
I only have one more small issue
instead of turning backwards to the right, it does a 315 degree turn
Sticks should spawn atleast with distance of 5 on X axis
but as u can see stick 2 spawned within 5 range
#๐ปโcode-beginner message
This is the code
So those are UI objects on a canvas? And they have a RectTransform?
yes
Couldn't get it done with raycasting as it really confuses me off how I would do it
like fine detecting if there is something else fine but i don't understand how I would manipulate that range between spawning points etc.
All i am trying to do is spawning those sticks atleast 5 float difference in distance on X axis
How big of a distance do you expect "5" to be?
I'm not sure but I think that localPosition is in pixels when dealing with UI
Fine here it doesn't look like it but
If I pick up more sticks this is how it ends up.
What is exactly 5? The position difference of those two overlapping sticks?
just need a loop lookin for valid positions.. after x amount of attempts break out of the loop
Its like One stick has Transform.position.x == 5 and other either 10 or 0
thats the difference im talking bout
Right. So what's the issue exactly? I don't see any stick that is closer to another stick than that
u do
lol.. makes my computer lag hard on Play() lol
I really don't, can you draw on it to point out which sticks are closer to each other than the first image you posted?
yeah just doing same thing on 2D and on UI
Anyone any ideas on how to not make it do that giant turn?
yup ๐ I don't usually mess around with 2D so i just replicated it w/ 3d.. Im using 0 - 1 as the min and max of the Y coord.. soo they spawn on a Plane..
All of these are further away than 5
First you can see it here debug, now I'll show u manually
yeah well
every stick should be distanced between every other stick with atleast 5
not just one to another and another to another
They are though. They are just overlapping, is that the issue?
if ur trying to space them out by 5 i would use 5 + the width and or height of the stick.. (soo u dont get overlapping at all)
and also with only X axis Y doesn't count
Realistically you want something like this
https://www.jasondavies.com/poisson-disc/
what is that
An algorithm that distributes objects how you want
well yeah but- that seems to complicated
i was just thinking of using collider-
but idk about UI and colliders, seems wrong
They are spaced 5+ on the x axis
Maybe you just want to check https://docs.unity3d.com/ScriptReference/Rect.Overlaps.html
how are those ones spaced
If this is what youre getting then yes I see the issue
it's random
Im using like random X axis
but it should regenerate if its like not far enough
foreach (var stick in StickUIs)
{
//checking if position is compatebale with other sticks.
while (randomXPos >= (stick.transform.localPosition.x - 5f) || randomXPos <= (stick.transform.localPosition.x + 5f))
{
//if not change position
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
foreach (var x in CachedXPos)
{
//check if its alright with any other alreadySpawnedStick x positions
if (randomXPos >= (x - 5f) || randomXPos <= (x + 5f))
{
Debug.Log($"{randomXPos} is inside the range |{randomXPos} >= {x -5f} or {randomXPos} <= {x+5f}|");
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
}
}
//if its far enough.
if (randomXPos <= (stick.transform.localPosition.x - 5f) || randomXPos >= (stick.transform.localPosition.x + 5f))
{
break;
}
}
}
and this is my code
just added that debug.log and it realized its messed up...
So first stick was placed at 10
other one was generated at -22 but changed to 36
Also this while loop will be infinite if it fails to regenerate when your inventory is full -> unity freezes
yeah I understand that
I'll have cap on how much stick u can take
and I'll lower the distance too so it don't looks weird either
I also feel like the || should be && instead
Please hit enter only when you have an actual message to send
Im sorry im kind of used to text like this.
didn't really work
seems overly complex..
foreach (Vector3 pos in cachedPositions)
{
if ((randomPos - pos).sqrMagnitude < squaredDistanceThreshold)
{
tooCloseToOtherSticks = true;
break;
}
}``` my example uses sqr distance threshold and just loops thru checking
instead of weird if/ or/ and/ conditionals
squareDistanceThrshold being float squaredDistanceThreshold = totalDistance * totalDistance;
totalDistance = the min distance i set to others
ok I'll try to implement that code but only to be working with X axis
How did you make this so smooth and have it not use up a billion percent of your cpu and ram?
I've tried a custom pooling system before and it went so poorly...
what is that .sqrMagnitude
i mean like It erros for me
does it need specific library?
oh no wait
in ur case its vector3
no..
yeah...
its the squared length of a vector
(it just cuts down on processing power to figure up distances)
hmm yea, it doesnt need any special using statement..
im only using Collections.Generic for the lists i use
it doesn't work for me because I do float x instead of Vector3 x
because well CachedXpos only takes X positions and I only want to make distance between X axis
oh its b/c it returns a float..
it should still work tho..
bool IsPositionValid(Vector2 position)
{
float squaredDistanceThreshold = minDistance * minDistance;
foreach (Vector2 existingPos in positions)
{
if ((position - existingPos).sqrMagnitude < squaredDistanceThreshold)
{
return false; // Position is too close to an existing one
}
}
return true; // Position is valid```
ahh gotcha
Couldn't you loop over the list of floats and compare position.x to it instead
foreach (var stick in StickUIs)
{
//checking if position is compatebale with other sticks.
while (randomXPos >= (stick.transform.localPosition.x - 5f) && randomXPos <= (stick.transform.localPosition.x + 5f))
{
//if not change position
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
foreach (var x in CachedXPos)
{
//check if its alright with any other alreadySpawnedStick x positions
if (randomXPos >= (x - 5f) && randomXPos <= (x + 5f))
{
Debug.Log($"{randomXPos} is inside the range |{randomXPos} >= {x - 5f} or {randomXPos} <= {x + 5f}|");
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
}
}
//if its far enough.
if (randomXPos <= (stick.transform.localPosition.x - 5f) || randomXPos >= (stick.transform.localPosition.x + 5f))
{
break;
}
}
}```
This is what I did before
You still had || in the bottom if statement
You want to check if it is far enough on the left side AND on the right side
yeah
Wait it might be okay, lemme thin
because logically when I do OR
it says either of one
so like if its less than 5 for example (its ok to be 6) right? and we don't want that
Alright nevermind, that if statement should be fine
Btw this logic tries to keep a distance of 10, not 5
yeah I know
Because you are checking 5 on each side
changing it to && didn't fix either
I don't see the need for the inner foreach loop though. Isn't the while loop already doing that?
no
So basically
when while breaks
Please write full sentences, let's not flood the channel
it checks if current stick's distance is good enough for next stick
Long time listener. 3rd time caller. I posted this a this a few days back. I have made some progress on other things. I am still stuck on how to disable movement on my players when the game is over. I had a few suggestions from before. I have not been able to figure them out. Would anyone be able try and point me in the correct direction again? I even tried to see if AI could help.
Shout out to Spawn Camp Games for trying last time.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
With that foreach I try to check if current stick is far enough with other sticks' positions
Okay, and what is the while loop for?
why not just disable the entire player script?
instead of worrying about input
just disable the thing tht moving the player in the first place
I tried that and I could not get it to work either. It was weird as I got it to work for the car spawner. I even tried to copy the code and insert the correct bits. I just could not get it to work. Let me try that again.
same thing but i think it only checked One stick, logically talking, if while checks one stick now and gets position of X at 5 and then after checking next stick turns Position at 4 because it was not valid and then checks next stick it would still allow to put it on 5
in my case i'd need to disable my SpawnCampController..
and at the end. u can tell that almost works.. but my camera is still moving around..
so id have to disable my camera controller script as well
also could u guys help me get those stones behind that brown UI?
They don't have Order in layers.
So I tried coping the same command I used to disable the carspawner. It won't work. I think it is because the playercontroller is on the prefab and not just in the game scene like the carspawner.
Configure your !ide so you can see your lines be underlined in red when you've made a mistake
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
using UnityEngine;
using SPWN;
public class GameManager : Singleton<GameManager>
{
public SpawnCampControllerLite controller; // needed to disable player movement
public ControllerCamera cameraController; // needed to disable camera movement
void Update()
{
if(Input.GetKeyDown(KeyCode.X))
{
EndGame();
}
}
// method to disable the things i need to stop player movement
void EndGame()
{
controller.enabled = false; // disable the character controller script
cameraController.enabled = false; // disable the camera controller script
Dbug.Stopped("Game has ended");
}
}
I think I know what I can do...
So Basically I can put like spawn and then like NextSpawnAtX float which will add up 5 everytime and we will spawn on that X but I don't think thats fast approach
if thats the case you'll need to either Cache that variable when u spawn it into the game..
or when ur ready to end the game use a method like Find to get the component to be able to disable it
and Also it won't really look the way I intended either.
Right on, I will try the Find first. Thanks again. I feel like this is one of the last major things I have to get done to complete this project.
Menu screens and Ending screens are always the worst lol
thats why i made my menu First
wheres the rest of the content?
iono lol ยฏ_(ใ)_/ยฏ
Same energy
hell ya lol
@willow shoal You're setting the bool an animation, not an animator type.
ok
void EndGame()
{
SpawnCampControllerLite myController = FindFirstObjectByType<SpawnCampControllerLite>();
ControllerCamera myCameraController = FindFirstObjectByType<ControllerCamera>();
myCameraController.enabled = false;
myController.enabled = false;
Dbug.Stopped("Game has ended");
}``` heres that same method using `Find` methods...
please ๐ note.. Find methods are not performant at all.. and shouldn't be called very often at all
but ending the game is a suitable use case imo
Alright so I don't usually spoonfeed but I'm bored and found this interesting. Something like this should work:cs bool foundAnyValid = false; float randomXPos = 0f; int maxTries = 1000; // Failsafe for (int i = 0; i < maxTries; i++) { randomXPos = UnityEngine.Random.Range(minX, maxX); bool valid = true; // The position is valid until proven otherwise foreach (var stick in StickUIs) { // Blocked? if (randomXPos >= (stick.transform.localPosition.x - halfSize) && randomXPos <= (stick.transform.localPosition.x + halfSize)) { valid = false; break; } } if (valid) { Debug.Log("Found valid: " + randomXPos); foundAnyValid = true; break; } } if (!foundAnyValid) Debug.LogError("Couldn't find a valid pos");
Could be some minor mistakes since I didn't test it with transforms but with a list of floats instead
same reason i built a 3D bounds based version lol
See how you don't need three nested loops but just two @lofty lintel
From the inner loop you break out as soon as any stick blocks the random position. Then the outer loop keeps trying new positions
If none of the sticks in the inner loop blocked it, we can break out of the outer loop since the position is valid
I even tested with a crappy GUI, those red boxes are the generated positions with halfSizeX * 2 as width
the only thing i dislike about mine is the attempted counter that breaks out of the loop to keep it from being infinite.. (the only way i know how to do it is to have a limit)
this is dope
idk what that is and ive alreday download the visual studio
That's what I did in my example also though
See the for loop with maxTries
Same thing
Oook I'll try implementing this
Downloading it is one of the steps, what about all of the others
soo its just normal for this type of thing?
Definitely
im just a bit ignorant on generative loops stuff like this
You see that a lot when doing these kind of "brute forcing" algorithms
alrighty.. thats all i need to know ๐ ๐
You could do that too but that would just pile them next to each other with even spacing, right? You wanted randomness
Ok now maybe im doing it wrong way
Yes that's why I don't wanna do that.
bool foundAnyValid = false;
randomXPos = 0f;
int maxTries = 1000; // Failsafe
for (int i = 0; i < maxTries; i++)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;//<------ Added this
bool valid = true; // The position is valid until proven otherwise
foreach (var stick in StickUIs)
{
// Blocked?
if (randomXPos >= (stick.transform.localPosition.x - 5) && randomXPos <= (stick.transform.localPosition.x + 5))
{
valid = false;
break;
}
}
if (valid) { Debug.Log("Found valid: " + randomXPos); foundAnyValid = true; break; }
}
if (!foundAnyValid)
Debug.LogError("Couldn't find a valid pos");```
Added that one line of code because Thats actually where I assign valid X position to spawnposition
You could add that line after the loops but it's fine
You might wanna try using anchoredPosition instead of localPosition though. I don't exactly remember how localpos behaves on UI/RectTransforms
there is no such a property
if its a sprite localPosition is fine.. if its a UI element (image) i think anchoredPosition is the better method
Right, you need to get the RectTransform component instead of transform
If it's even needed, that is
theres no property for a gameobject/Transform ur correct..
but if they are UI images u should be using the RectTransforms
Its gameobject with image component on it
ya, i get that.. but when placing them.. its usuaslly better to use the RectTransform of the gameobject
this is how I add them StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
GetComponent<RectTransform>() instead of transform
{
valid = false;
break;
}```
ya, but u should probably just have RectTransforms as ur types in general
Or better to store the StickUI's with their UI type so you can probably access their .rectTransform directly
You should cache the reference to RectTransform instead of calling GetComponent over and over
oh ok
we get that alot where people put in what they think is good coordinates.. but b/c its a UI element they wont appear where people expect..
thats why they'll get suggested to use RectTransform component instead
oh so thats common case
So I got it to work with the find by looking for tags. It stops them. If I hit replay it works. Now they skid to a stop. I need to kill the forward momentum. Thanks for helping with this. I am super close now.
but like Osmal mentioned earlier.. it may not even be a problem for your use-case
just mentioned
you can set its velocity to zero ๐
Yeah, that is what I am trying to do now.
controller.Move(stopVelocity * Time.deltaTime); // Apply zero movement
u could put a method in ur CharacterController script that calls this line ^
before its disabled the important part being before
Right on
Thanks again
stopVelocity is a vector3 ofc..
Vector3.zero
its odd that ur player keeps its momentum tho...
my CharacterController stops dead in its tracks.. even whether im grounded or not
so I did this.
{
StickUI.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
}```
the matrix
I'm facing a strange bug where a boolean is never changed for a single script and it all points to it being changed.
I even had used a Debug.Log and there it says the value is false, but in Update the value says true 
for me stickUI is public GameObject StickUI;
Prefab.
I am sure that if you saw my whole project you would shake your head in disappointment like my parents do. It could probably be made so much more simply with someone that has experience.
u can instantiate it as a RectTransform
public RectTransform StickUIPrefab;
you gotta provide more info than that
right..?
If you log it and it says false, it's false. How are you seeing it as true in update?
no one builds their first dozen projects perfectly structured
Show full !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's the bug I'm facing .. I have no gosh darn idea
That follows with this error
thats because u probably have something before that Instantiate
Instead of storing it in a variable of type GameObject, store it in a variable of type RectTransform
Thats what I did
Show the full line
how did quaternion not error btw?
whatever method you are passing the return value of Instantiate to expects a GameObject not a RectTransform
Yes i read that
Unity.Mathematics.quaternion
change the expectation to RectTransform.
Ok wait guys I'll send the whole code now
You don't know how you're seeing the value as true?
thank you
!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.
A tool for sharing your source code with the world!
it also has an implicit cast to UnityEngine.Quaternion. but also fun fact about Mathematics.quaternion, it's Euler method expects radians instead of degrees for whatever reason
check this out
It must be some kind of classic Unity bug
I don't see any booleans in here
i immediately removed the namespace ๐ im not ready for another math library
alright
It's literally impossible
you should also include the InstanceID when printing info, or at the very least add the context parameter so you can click and see which instance those logs come from
Okay, so, the log in OnResume is printing, so that's how you're checking that it's false. How are you sure it's true in Update?
There's no log in there
the amount of times i've thought the computer was lying to me
I've refactored the code sooo many times
Hey It worked. Thanks for the help. You have been amazing. I really appreciate your time and effort.
only went so smoothly b/c of ur ettiquette
so thank urself ๐ช
https://paste.ofcode.org/APuXHwM36PjbMCYRyJR5ku I have this code I wrote to reset the characters position when it comes into contact with anything with a contactLayer but it wont work even though theres no issues with how the code it written, need some help
And now when updating the Unity version to 2022.3.48 it never changes the state to Playing 
Okay, Unity ..
This isn't Unity's fault
The code does exactly what you tell it to do
It is if the version matters
I want to call a function when a gameobject is Enabled/Disabled, How would I do this?
changed that but still...
Chances are you have a race condition and it will change literally every time you restart the project
100% of the time you've accidently coded it to lie to you
other than that.. it is what it is lol
Start is called once at the beginning of the object's lifetime. if the object is not touching those layers when it is spawned then that bool is never true.
because the order of functions like Start and Update are basically random
OnEnable or OnDisable
Can confirm that was an order of execution error.
How would I use it in this sit.
public void ResetFur()
{
MonkeMesh.material = FUR;
}
public void ChangeFurToFall()
{
MonkeMesh.material = FallFur;
}
I don't know what this has to do with enabling/disabling
But however .. There is no way that this bug is order of execution since it subscribes to the event
Unless it magically unsubscribes
void OnEnable()
{
ResetFur();
}```
When GameObject FallCosmetic is active, MonkeMesh.Material = FallFur
If you want that to run when it's enabled put it in OnEnable
https://docs.unity3d.com/Manual/ExecutionOrder.html heres all the methods and when they run
Ok i'll go now, i'll fix this later.
It detects paused as false for EVERYTHING but a single darn script and I have no special code there. That's what bothers me.
ty guys!
I put that information in my GameManager.. and i have it manually added into the execution order to run first... (all other scripts get its data from it so it must be updated first)
not a solution for all situations.. i just wanted to mention it
hey quick question but does anyone know how to type script in unity im new to it
OnResume is called and I had a Debug.Log tell me that the value is FALSE.
However in Update the value says that it's true
As if its passed by value
Let's change your logs a bit. Inside of GameStateChanged, use this at the end of the function:
Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] Game state changed to {gameStateKind}, IsPaused: {IsPaused}");
Inside your script that's causing a problem, at the top of Update:
Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] Update is running, IsPaused: {IsPaused}");
wdym? like are you asking how to create your scripts? if so then start with the beginner courses in this channel
how do i get to beginner course?
In the pins, and also !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
in the pins where that?
I don't see the GameStateChanged message in here, and that "Paused value True" doesn't have the instance ID
Hold on, let me record.
So it doesn't show anything
All it shows is something has its paused value set
but that might not be this thing
in the channel
"view discord pinned messages"
what channel? im dumb sry
the one you're typing in
oh ๐
remember how i specifically said "this channel"
oh
A tool for sharing your source code with the world!
is the um beginner scripting thing?
This first log, @vestal isle
I don't want to log every single object that inherits the script, but only the specific script I'm looking for
So then how do you know that this particular instance has it's IsPaused set
You could also override that function in this script and check it there
print the name and instance ID in that log you have inside of Update too. it's rather suspicious that the logs show you have a positive instance id. it's typically negative for instances of a prefab (or just non-assets)
It is one of the logs I posted.
Where's the one in GameStateChanged
Oh, you mean that.
I very specifically included two logs to use
I see, my apologies
so that you could compare the InstanceIDs
Can you show the inspector of the object that has this script on it?
Also, just to be sure, your log in update is before the return, right?
Okay, just making sure
Add these functions to your player script. These will run instead of the normal OnPause/OnResume of the parent class. Make sure it's getting both messages.
protected override void OnPause()
{
IsPaused = true;
Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] is pausing");
}
protected override void OnResume()
{
IsPaused = false;
Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] is resuming");
}
sorry for the late reply but do you see anything else? I moved it to update void but it doesnt work. I have the player and floor layers set to contact (just trying to make a bogus flappy bird so the players in the air which is why I have contact set to false to start)
Are any of these other ones child classes of PausableMonoBehaviour
here ya go.. Crash Course..
Every other script is affected by pause but shooting is the only script that isn't
Yes, all enemies derives from it
You haven't sent the shooting script code yet
The one in your bin was Player
well for starters, have you done literally any debugging?
also why are you using that method to check for collisions instead of any of the better options?
j/k ofc.. theres just soooo much to know.. but yea check the pins.. and if ur a visual learner
https://www.youtube.com/watch?v=_cCGBMmMOFw&list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw&ab_channel=SebastianLague this series helped me alot @charred cedar
Oh, I was still looking at the multi-tabbed bin you sent first
This might be the strangest bug I have ever had in Unity
or it's just me .. But impossible .. heh. ๐
I'm pretty sure what's happening here is that there's multiple IsPaused variables due to inheritance shenanigans. There's PausableMonoBehaviour.IsPaused and PlayerShooting.IsPaused and it's setting the first one inside of PausableMonoBehaviour but using the second
yes, and because I don't really know what im doing. I'll figure it out eventually, thanks though
I'm just trying to figure out why and how we can check
well what debugging have you actually done? because there was nothing being done in the code you previously shared. you just dropped the code and expected someone to just give you the answer
Maybe I can try with an interface? ๐คทโโ๏ธ
or abstract to force the inheritor to declare it
Try with these overrides - it might even end up solving the problem if it's what I think is happening
I did but I'll check it again
also happening on Unity "6000", so it's probably strange Unity behavior
This is strange C# behavior. Inheritance does some weird things sometimes if you don't do it exactly right
I don't see anything awry but I also have run into this problem myself before so I am prone to miss it
deleted it, I had a few different things that I tried for a while but didn't work. I Deleted them because well they didn't work and becasue the problem felt fairly simple. I just figured since this is my first it was a simple mistake hence why I dropped it in here after deleting them.
Ill leave it next time, again thanks for the help either way
yeah for future reference, do not modify the code when sharing it. that includes leaving your debug statements in so we can actually see exactly what you are doing.
ok that is odd
Something else is pausing it right after it's resumed
Yeah, found it as well
Did you perhaps subscribe to the wrong event somewhere
lets try with caller attribute
can you not just look at the stack trace?
That is true
Would that show what called the function that invoked the event? Or would it just go cold at the event?
should show where the event was invoked
Yeah, check that
looks like OnPause is subscribed directly to an input action
And due to the volatility of execute order, most other scripts are doing OnPause, OnPause, OnResume, while this one is doing OnPause, OnResume, OnPause
Oh my god, I know what it is
the input system was calling OnPause function obviously via SendMessage
๐คฆโโ๏ธ
You have a button named "Pause" dontcha
And a PlayerInput component that sends messages
That's so stupid and so obvious
this is why i generate the c# class and manually subscribe to events. can't have SendMessage invoking private/protected methods that way
Yeah, that's what I used to do. But I grew tired of it, too much init code needed for it.
Thanks everyone who helped, respect y'all. ๐ฉต
Remember - it's always the human's fault. We're very good at making complicated problems
eww, SendMessage . . .
yeah i prefer the manual setup over the reflection lol
Confirmed it works now.
I should for sure use manual way next time. This was a pain
why is this code unreachable?
` public void RemoveItem(Item item)
{
for (int i = 0; i < slotList.Count; i++)
{
int slotIndex = itemList.IndexOf(item);
Destroy(slotList[slotIndex].transform.GetChild(0).gameObject);
itemList.Remove(item);
break;
}
}`
- !code
- it generally helps to point out which line the warning/error is on
- you break on the first iteration so that being a loop is completely pointless
๐ 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.
this one mate
for (int i = 0; i < slotList.Count; i++)
that warning should be on the i++; part specifically, which happens after the for loop iteration. and read boxfriend's 3rd point
please read the entire message
๐
What's the point of a loop that only runs once before breaking
its fine i just got rid of it its 1am give me a break๐
So I have a object with a RigidBody and Box Collider that has a chance of falling through a Terrain, and it's only 2 meters off the ground. There something to avoid that?
What provides that chance?
Likely you are moving the rigidbody incorrectly (with transform instead of rigidbody) or it's moving too fast and you don't have continuous collision enabled on the RB
Oh the object is just following physics, though I did forget to add I'm randomly rotating it and applying velocity on spawn (basically flinging it a little). But if I need continuous collision then that'll be what I need to do then.
If you're rotating the transform directly, it could cause issues as well. Make sure you rotate it via the rb torque, angular velocity or move rotation.
Yeah I was directly. Seems fine during a Start for how this object is placed in particular, but updated it regardless.
void Start() {
Rigidbody rigidbody = GetComponent<Rigidbody>();
if (rigidbody != null) {
if (fling) {
rigidbody.angularVelocity = RandomVelocity(flingRotation);
rigidbody.velocity = RandomVelocity(flingVelocity);
}
if (randomAngle) {
rigidbody.MoveRotation(UnityEngine.Random.rotation);
}
}
}
can someone tell me how to fix this cuz I don't understand it
is that runtime screenshot?
You have probably another instance of this script
let me check
I dont see another script that has the AI location selector script
Did you try searching t:ailocationselectorscript in the scene?
Click the clear button
Im not even sure if a serialized array/list can be null ๐ค
Show the contents of the script
ok
Oof, is this decompiled
yea :C
I opened a new decompile that is the same one
at it looked fine
idk what went wrong
Just for future reference, decompilation isn't really an allowed topic here.
alright then
i would remove the decompiled code . . .
Anyone have a suggestion for the best way to go about starting a single coroutine do I just use a boolean to make sure it doesn't spam it? Or is there some kind of special unity library function for this
there is no best way; you should start one when you need it to run. if the coroutine runs in Update, you assign the coroutine to a coroutine variable and check if it's null before starting it. if null, it has not started; if not null, it is currently running . . .
Also, I can't find anything on a resource to directly just import a new animation onto an existing rig. Is there a method or do I just reupload the same rig with more anims and replace all the scripts and values on it?
Note that you still have to set it to null at the end if the coroutine completes
Appreciate that though
didn't know about the null stuff
So it's kind of a self boolean
yes, setting the coroutine to null at the end of the coroutine method is important . . .
dunno, i haven't done that myself. maybe #๐โanimation would know . . .
Oh good idea. I just made a copy and pasted all the components for now
tryna wiggle my way in with the random asset stuff while I focus on discovering new code lol
You mean yield return null; ?
no, that is yielding (pausing execution until the next frame). you actually set the coroutine variable to null . . .
Ladies and Gentlemen
it works
i haven't had a sigh this sweet in weeks
now next steps are:
1.Lerping\SmoothDamping this thing
2.Stopping this at collision
IEnumerator Heal()
{
if (animator.GetBool("IsDowned"))
{
Debug.Log("Healed!");
currentHealth += maxHealth / 10;
healthBar.SetHealth(currentHealth);
}
yield return null;
}```
```CSharp
if (currentHealth <= 0 || animator.GetBool("IsDowned"))
{
if (currentHealth < 0)
{
currentHealth = 0;
}
if (currentHealth >= maxHealth)
{
currentHealth = maxHealth;
animator.SetBool("IsDowned", false);
}
healthBar.SetHealth(currentHealth);
animator.SetBool("IsRunning", false);
animator.SetBool("IsJumping", false);
animator.SetBool("IsDowned", true);
if (Time.time >= nextTime)
{
StartCoroutine(Heal());
nextTime += interval;
}
}
}```
It works as intended except it fires off anywhere from 5-20 calls right when the healing starts. I assume I setup the coroutine or timer improperly, but require some guidance if possible please.
https://gyazo.com/4de55036db59ecf297e0cc9351044e44
private int interval = 1;
private float nextTime = 0;
``` ^ is used for my timers
show the full code !code
i have no idea whats going on
๐ 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.
read the bots message...
Oh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ty
the timer normally works as intended minus the initial misfire in the first second, but I'm assuming it's that or how I null the coroutine
why can't I name a function โ while I can name a function ฮ
why would you name them that ๐ค
because they read better than Mathf.Sqrt and Time.deltaTime
its either reserved or seen as an operator
not sure which in c#
think its just that they dont support arbitrary symbols
yeah or its not unicode
Because a identifier must start with a letter character, and sqt is symbol,math, whereas delta is letter,uppercase
You shouldnโt lol
and neither symbol or math are included in Identifier_Part_Character either https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#643-identifiers
Anyway, that's the complete answer to your troll question
symbols make the code less readable . . .
They are well aware of that
that should be the least of your worries . . .
what is less readable about this
They also break naming conventions. You canโt use special characters in code other that @ symbols
do you think Vector.add(Vector) is more readable than Vector + Vector @cosmic dagger
why would you assume this is a troll question?
Because it's obvious that it's an unreasonable thing to type
we use a snippets file that makes :dt auto type it
not a worry at all
its in fact easier to type than Time.deltaTime, lol
This is illegal
Only if you didn't also make a snippet for that
Right yeah, snippets were the solution we went with for your criticism
its a good thing we can do that.
its workspace wide so all members of the team have it automatic on their machines btw
zero config
Do those snippet files work on other IDEs?
no, we're all using vscode though. other IDEs support snippets though
+ is an operator, and yes, it is easier to read. i couldn't tell what the square root symbol was doing in the pic, and not everyone will know what the delta symbol is . . .
that is a very small criticism that is outweighed by the readability benefits in our opinion
you couldn't tell that the square root symbol was doing square root?
you guys are trying to be haters, lol
Well colour me surpised that it's not a troll, but yeah, it's not gonna work for non-letter characters unless they're also in the spec I linked
i agree lol. this is top tier hating. i really like the sleek look of the single character replacements
no, i mean, i didn't know what values were being used in the square root . . .
not everyone will know what the delta symbol is . . .
it would take them 2 seconds to learn the symbol and then have it dedicated to memory forever
our team is 4 people also
Special characters are a violation of naming conventions. So are single character identifier names. :P
yeah i mean you might go "woah how tf is this allowed?" but you obviously would have a good idea of what it's doing... Its a Square root..
code looking unfamiliar doesn't mean its not more readable, once you familiarize yuorself with it
and then you hover your mouse over it, and you see the intellisnse "alias for Mathf.sqrt()"
yeah this was my point about conformism earlier. "MIcrosoft says so, and everyone else does it this way" just isn't compelling to me. I'm not working on an open source project with 200 people. Looking like standard C# isn't very valuable to a 4 person team
no hating here, we're just giving a general view of its use. a snippet could easily be made that auto-typed Time.deltaTime instead of creating a snippet that gave a delta symbol which pointed to Time.deltaTime, just seems like an extra step that's unnecessary . . .
the typing isn't the issue motivtaing us. Its the readability. We think Time.deltaTime is an eye sore that makes our lines of code too long, forcing us to split stuff up into multiple lines, making our functions longer, etc...
the fact that you have to familiarize yourself with it for it to become readable is the problem itself. that's really our point. it's cool that it works, but definitely weird . . .
Time.delta would have been acceptable I think. But Time.deltaTime... tf were they thinking
how much code are you writing on a line that Time.deltaTime takes up so much space. typically, lines are less than 120 characters?
I like stupid shit like making the division operator for strings act as path concatenation, and other silly things like that, but I personally think that outside of it being a self-contained library "neat" isn't much of a value add. But whatever, nobody is stopping you and if your team likes it that's great
when you join a new codebase, there will be things you have to familiarize yourself with. Like functions or variables etc. This is a very very easy thing to learn that takes 2 seconds
also, i'm curious, how do you write fixedDeltaTime?
there's almost never a reason to use fixedDeltaTime anyway ๐ it's so rare to need it
didn't know that was a thing. I'll probalby do ฮtfixed or something
true, but i can't see a pretty way for them to write that . . .
:fdt -> fixedฮt
for example this line of code fails to fit
but if turn on my symbol mode...
its all on one line now
ah man, you guys could've done better. you reversed the name . . .
i was, at least, expecting this . . .
sure that is good too
what's going on with the Vector3 replacement
bro, even the Vector? omg . . . ๐ฒ
lol if you're gonna go all out... give me a sec
Wrap it
we reject word wrap
it is important that code reads the same for everyone
so we have a team rule not to use word wrap
and keep things fitting on 1 line
Someone I follow uses a wild amount of ligatures https://www.twitch.tv/videos/1604954734?t=2h1m41s
I just meanโt to press enter to break up the line
right but i think it reads less fluidly.
Quick question, but is there a way to check if a collider's, well, colliding
even if there's no rigidbody?
the ligature list scrolls lol
usually, creating an entire variable, then using it an equation, reads less fluidly than just having 1 short equation
your brain interprets it as two steps
are you limited to under 90 characters per line?
we are self-limiting ourselves to "this code must fit on a 13-inch macbook at default vscode settings"
whatever line count htat is
yeah, fuck it, go all out . . . ๐
incredible
You donโt have to create a variable. It isnโt python
its just sort of jagged now
better I guess
but still
not even close to how readable and sleek this is
and now that im using a visual substitution extension, you can just type Time.deltaTime
the real text is that.
Only with the collision callbacks--if a body (something with a rigidbody) hit it.
Either that or you query the scene manually
wait, what's the ^ for? isn't that already a symbol?
its &&
logic symbol for and
๐ค
Can my rigidbody be kinematic and still trigger a collision?
thx
yea, you lost me with the last two symbols. this looks like MonoBehaviour is magnetized or pointing to Jump . . .
@cosmic dagger
meanwhile I'm over here making my variables as verbose as possible
my object IS a kinematic rigidbody trigger
void OnCollisionEnter(Collision collision)
{
Debug.Log("You're colliding yo");
}
}
and i added this snippet of code in there
its the logic symbol for subset!
but it's still not printing that debug
That's not a trigger message, that's a collision message.
yeah, this is foreign to me. that looks like a protractor for an angle. i would have thought it meant angle or the 'A' was upside down. this is already too many symbols for me . . .
you learn this symbol in computer science degree, its the "forall" quantifier in logic
Where can i read more into that?
oh responding to wrong person
or is it the compass, not the protractor . . . i think . . .
it's a funnel
I'm glad you enjoy this level of unreadability lol
it is a level of huge readability for people who are familiar with the symbols lol
I'm very glad I have programming so I don't have to learn symbology to do maths
all programming comes from maths /shrug
i like the idea of gatekeeping my codebase with the formal symbols of everything a bit tbh
"dont touch this code unless you are a wizard"
If I learnt programming before being taught maths I would have learnt so much more maths, but they really had to just make everything theoretical with an expanding set of unreadable symbols
yeah
how is this unreadable? this took me a week to learn when i was a sophmore in highschool self learning discrete math lmao
That's good for you mate
im not saying that to brag, im saying that to show how easy it is if you try
yeah, i'd need to study a legend or symbology (semiology) to know any of these symbols. glad you lot do . . .
i'd be left at the gate . . . ๐ข
I know what the symbols mean, it's still a self-centered and unapproachable style. Doesn't mean they shouldn't do it, but if this was how C# was written more broadly it would be much harder to learn.
my problem is, i'd have to remember symbols every time i'm reading or trying to code to know what 's going on. that will slow me down, and make it harder to write and focus on the code itself . . .
i used to be the same, but after doing basic discrete proofs for about a month, i havent forgotten them since. and this was when i had very little coding knowledge
anyone who knows a skillset can say, "it's easy if you try," but each skill has a different learning curve and barrier of entry for the general populace. my friend, she's a polyglot, and says the same thing, "learning any language is easy, if you just try . . ."
great, now i have to lookup discrete maths, what ever that is . . .
honestly im of an opposite opinion. anyone can learn anything given that its not too complex and they have the right learning materials
its very basic stuff dont worry ๐
unexpected density decreases readability because of unfamiliarity with symbols vs words, and that'd probably be where I fall down. It'd be like reading shaders where they've named everything single letters. I'd have to come along and expand them if I wanted to work with it
maybe it'd be fine for myself to use that much, but I'd hate to drag a team along
especially if I had to make any new hires haha
complexity is based on an individual's perception of said topic. i've definitely seen people struggle with a simple instruction or topic which they saw as complex. i've even done so myself . . .
when i first started programming, i found everything to be of "unexpected density". its extremely arbitrary imo
It's not arbitrary when you have standards and have been using a language with them for 10 years
which is why i also said "given the right learning materials". this statement, from my perspective, includes a teaching system that is easy to understand for anyone
similar to that one Einstein quote
if you cant explain something to a 5 yr old, then you dont really understand it
true; good luck finding/writing that system, lol . . .
i never said it had to be "one-size-fits-all"
learning how to program felt easy for me; it was like reading a book. i do feel anyone can learn how to program (of course at different levels). the hard part is the logic behind it all. it's the . . . how is A going to sync with B. how do we fit C and D into B. does D need A? it's like putting a puzzle together with pieces that you (still need to) build . . .
i agree 100%. and since anyone can easily learn to code, they can also learn discrete math or even real analysis, since all are so similar
its simply a matter of perspective
yep. for some it's 2D, 3D, or 4D . . . ๐
yeah the idea is that we want you to already know that if you're working with us
to the programmers who already know these symbols, it is faster on their eyes to read the symbol version than the verbose Time.deltaTime version
so its a tradeoff of who we are priotizing. I want faster readability for the pros on my team, even if it makes my code a bit alien and scary looking to the less experienced/knowledgeable developers
it is elitist for sure. But we think thats a good thing
so uh idk if this would be ui help or coding help cause i have no idea what's going on. i have a textmeshpro menu that lerps positions when the button is selected and the code seems to be working fine, but when i press the button it goes back to its original position? it works fine if the buttons are set to color tint or animation instead of sprite swap, but i need it to be sprite swap. i'm not entirely sure what i'm doing wrong?
the buttons are on a grid layout group with a content fitter which i suspect might be fucking with it but i need those too
ok as i wrote that and realized it might have been the grid layout group i checked it and it was and idk what to do about it
sorry guys, where do i ask for help, I'm having issues with my project
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
your lerp on Color is correct but your other 2 lerps are not.
Lerp is current = start,end,t
thank you
hello I've been trying to code this solar box puzzle
i got to rotation to working in a separate script but i can seem to get the solve function to fire off even tho all the transforms are at the correct rotation angles
using System.Collections.Generic;
using UnityEngine;
public class SolarBox : MonoBehaviour // PascalCase is Conventional for class names in C#
{
[SerializeField] private List<Transform> _rings;
[SerializeField] private List<float> _correctAngles;
private void Update()
{
bool isFail = false;
foreach (var ring in _rings)
{
float currentAngle = Mathf.Round(ring.rotation.eulerAngles.z * 2f) / 2f;
//Debug.Log($"Current Angle: {currentAngle}");
if (!_correctAngles.Contains(currentAngle))
{
isFail = true;
//Debug.Log("Angle is incorrect.");
break;
}
}
if (!isFail)
{
OnSolved();
}
}
private void OnSolved()
{
Debug.Log("PUZZLE IS SOLVED!!!");
}
}```
2 points.
using eulerAngles in your calculation will probably not give you the values you are expecting.
using .Contains does an equality check. Never do equality checks on float variables
any advice on both points
first one is difficult, you would need to maintain your own rotation vectors for each ring.
second one, dont use .Contains, make a for loop and compare the difference between the numbers
even for that .Contains point, it seems wrong to use this. this seems like it doesnt matter if the rings are in a specific rotation, just that any ring has a rotation from this list. is this intended?
With 2 rings and the goal being ring A = 90 degrees, ring B being 45 degrees, the solution could be or (A=90 and B=90) or (A=45 and B=45)
You should instead check the same index of your _rings and _correctAngles. Meaning rings[0] checks the angle at _correctAngles[0]
Hello, im relatively new to unity and im following a multiplayer fps game tutorial and i keep getting this same issue no matter what tutorial i follow (im using Photon Pun2) the code thats causing the error is this: Anyone know how to fix it?
it prints creating controller then it errors
InvalidEventCode | Used when an event with other code other then the treated ones is received by the plugin
Validate your Photon events or something, apparently
in the tutorial im following (i copied his code exactly) it works for him and this error only seems to happen to me. cant find anything on it online or any fixes. it wont let me js enter the prefab itself since it takes a string so idk what to do
Sorry, no idea. Photon is not something I'm familiar with but I suggest you validate the events/strings/whatever you pass to it
I assume the tuturial has a git repo you can compare with
Alternatively ask in #archived-networking
Ok, ty
i have a question
i am doing something like this
if (!UAEFileRoot.Find("AssetsFiles").Find("Managed"))
this is an if statement
now inside the if statement i am checking if the gameobject has a child or not
do i have to do it like this
if (UAEFileRoot.Find("AssetsFiles").Find("Managed") == null)
or this can also work
if (!UAEFileRoot.Find("AssetsFiles").Find("Managed"))
helps are appreciated
Normally it works
https://docs.unity3d.com/ScriptReference/Object-operator_Object.html
it has an implicit conversion to bool, so you shouldnt need to type == null but i sometimes do it anyways because i dont always find it intuitive
Also, I'm unsure on whether or not UAEFileRoot.Find("AssetsFiles") can return null, if you use a method that may return a null reference, and you still want to run code out of it, you may do
UAEFileRoot.Find()?.Find()
thanks for the info
Tell me if I'm wrong, I'm a bit new to C#
it can return null
null conditional (the ?.) shouldnt be used on unity objects
So you may not ALWAYS find this specific type
if the gameobject doesnt exist
then it will return null
no matter what
Is there a reason for that?
it doesnt use unity's implementation of a null check, which is implemented in ==
so if you use null conditional or null coalescing then you can get it to return true, when the object was already destroyed. unity will return false if its destroyed
Oki good to know, thanks
im not sure it actually matters in their case, because the only issue i know is if the object existed at one point and is destroyed. but just better practice to not do it rather than be unsure of if you can
really quick sanity check if this makes sense:
using UnityEngine;
public class DontDestroyOnLoadMono : MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
}
any votes against?
Why wouldn't it? It's too simple to say anything about it.
reason why i ask - thought there is some built-in tag or something to mark objects without need of attaching such script, so maybe that absence has a reason
Not something I'd really use. An object that needs to be in DDOL will have other scripts than this. Those other scripts can put it in DDOL themselves
of course, matter of preference, but having it separate is more mainainable for me
There isn't anything built-in for that.
๐คทโโ๏ธ it's exactly as maintainable as if you didnt separate this. Imo this is just bloat
it depends on an object, i came with that solution for GlobalVolume for example, that has no custom scripts other than that
Maybe just parent it to another DDOL object instead.
Or are you gonna put component on every single object you want to be DDOL?
parenting is good idea actually. About other objects - that would depend if their other scripts should worry about this or not
Hold up wait I want to look at unity learn !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hey... Can you help me, please?
Does your rigidbody have extrapolation enabled?
If not, how are you moving it? Charactercontroller or rigidbody? Show code
How to enable it?
player movement?
because of the code
Code "Move": https://hastebin.com/share/piyulofuju.csharp
Code "CameraLook": https://hastebin.com/share/ikuhofiwuh.csharp
You are using transform.Translate, dont move a rigidbody with transform. It will lead to weird physics like this
Use rigidbody.velocity or addforce instead
As a bonus, you might want to use an early return instead of nested if-statements: if(isFrozen) return;, same with the pause check
Helps with readability IMO
Get rid of the transform.rotation too, use rigidbody.MoveRotation(Quaternion.Euler(x,y,z)) instead
What about code of Camera Looking?
i think there are some error in my code but why dont the ide higlight them?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
Didnt check that yet, fix the mentioned issues first
Camera code looks ok
Here my new code:
https://hastebin.com/share/epeceseluf.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Since @verbal dome is around
No problems for you today
it just worksโข
Thanks for you help, man
Nice!
Yeah, is the issue gone or still there?
It still there... Maybe something to add to rigidbody?
Try moving this into FixedUpdate: rb.MoveRotation(Quaternion.Euler(0, player.transform.eulerAngles.y + y, 0));
And enable Interpolation on the rigidbody
Is the current issue exactly the same as in the video you posted?
Also might wanna use rigidbody.rotation.eulerAngles instead of player.transform.eulerAngles here
All update in FixedUpdate?
Nah just the part where you apply the rotation
And maybe the velocity too but I think it's fine in Update
Generally speaking you should do physics stuff in FixedUpdate
does transform.GetComponentInChildren also return it if its on the transform?
yes
alright
you don't even need the transform. .. you can just do GetComponentInChildren<T>()
i need to look on a specific object
if its on the object that the script is on then yeah ik
i meant like specificTransform.
righto
It probably used to be a monobehaviour and you added it as a component, then removed monobehaviour
right i know why
i copied this system from my old game
the class is called WorkStation
but the script is called WorkBench
Filename should match the class name unless you are using newer unity versions
yeah i know
more specifically, it must match the name of the MonoBehaviour contained in it. it has literally no effect whatsoever on plain classes
and even in the latest versions, if you have multiple types in the file it should match the name of the MB in it (still no multiple MBs per file, but that should be avoided anyway)
Yes! It's working, but the controls are broken...
what'd be the difference here?
If you have interpolation enabled, one of those returns the interpolated rotation and other one is not interpolated
I forgot which way around it is
Thank you for your helping
Broken in what way?
@rich adder (to continue the discussion)
well, for example, if I press D, the character goes to the right, but if I turn the camera to the left, then when I press D, he goes back... And the jump broke, he doesn't jump at all now
eg
Vector3 bottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, Camera.main.nearClipPlane));
transform.position = new Vector3(bottomLeft.x, bottomLeft.y, 0);```
if its 2D you prob dont even need nearClip plane
each time in the for i am creating the block, setting the color as black and i want now to move the block
its 2d
I see, you need to rotate your moveDirection by your look rotation
okay if camera is ortho then no need to worry about the nearClipPlane but the process is the same. Screen / View to World will translate your screenpose (0,0) to world equivalent
right click, Find All References or something
forgot what the option in VSC is
Can I send my new code of player movement?
Sure
You need to do something like cs moveDirection = Quaternion.Euler(0, yAngle, 0) * moveDirection;
So you rotate the move dir horizontally according to your rotation
yAngle could be your rigidbody's y angle or your camera's y angle
ok so in this case i want to save the value for the first block, then the other need to be placed without with the +y and +x, right?
oh thats weird..maybe its counting that one as its own thing?
You could also search by name/keyword in all files in solution
(The reason you didn't have to do this before is because you were using Transform.Translate which works in local space by default)
https://hastebin.com/share/ajewenonoy.csharp Here my code)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
right
it was an old SO
Yeah, do the rotation that I just posted, right after you create moveDirection
sneaky!
i was coming up with a system which i scrapped
Oh would think interaction type to be an enum
look interesting as SO though
And for the jumping, you need to disable the walking rb.velocity when you are not grounded (falling or jumping), otherwise it will override your jump velocity
yeah with an SO its easier to add more
specific ones
wdym by that
very true
But then you probably also want to be able to move in the air, you could use AddForce instead of rb.velocity for movement when not on ground
how does it know that it should increas eand put the blocks one near the other?
I would assume the loop. Each iteration will add + offset
thats typically how you spawn stuff
Can someone please explain to me why Input.GetKeyDown is detecting the desired button sometimes, instead of everytime
i can provide the code
show code
oh ok
depends on where you're calling it, conditions etc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float jumpForce;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(rb.velocity.x, 1 * jumpForce));
}
}
}
https://hastebin.com/share/gizefijala.csharp
by the way, the last code worked... I just forgot to put interpolate in rigidbody ๐
What do you think? Is it need?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
get it out from fixedupdate
i told you this before (i believe)
dont check for single frame inputs in FixedUpdate, you need Update
FixedUpdate runs at a specific interval
ohhhh okay thank you for explaining
Is what needed?
and FixedUpdate is framerate independant and it runs on the physics step so you wouldnt get it every time
this code
yeah usually its something like
Vector3 position = startPosition + new Vector3(x * (squareSize + gap), y * (squareSize + gap), 0);
etc
i thought you were telling me to take it out yesterday because i was using postion which is not physics based, i didnt realise you were telling me to take it out because of that
What code exactly lol
You posted the whole script, yes you need it
no, I was talking about the inputs
here give me a minute
He's changed a little bit... For example, there is no FixedUpdate.
If it works like that then it's fine
Btw you can also just enable interpolation from the rigidbody inspector but setting it from code is ok too
Is the essence of the code the same? Add a rotate that you posted?
wait so do i need to take my horizontal movement out of FixedUpdate as well?
no, just the inputs
you take the keycodes out
so this is okay, correct?
void FixedUpdate()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
}
yes this is correct
sorry i didnt understand
any physics item like RB.Addforce, RB.Velocity should go into FixedUpdate due to it being on the physics step
Now im very confused as to why this doesnt work.
When a Ball (Prefab with the shown Code attached) touches the Player with the "Player" tag its supposed to Destroy itself. What did i do wrong?
thats why I thought I should put my jump code into it aswell because it uses AddForce. Is it different because it's a jump instead of constant movements?
I just want to understand why its wrong, so I actually learn
you would keep your jump code in there just take the inputs out , give me a minute while i give you an example
im having a brain fart rn
it works now that i put it in void Update though and it did fix my issue
you dont want to put addforce in update since it will give unreliable results
bruhhhhh why is coding so hard ๐ญ
its not im just having a brain fart to help rn, so give me a minute ๐