#💻┃code-beginner
1 messages · Page 374 of 1
Have you verified that it's yielding non stop - no your eyes or it running slow does not verify this.
Does it operate more than once per frame? Print the number of iterations before the yield statement is called.
Alright, I can't help you since you aren't willing to debug 👋
k bye
So if anyone else wants to explain how to yield my coroutine properly, let me know please. Thanks
is this the same code you still have?
Yeh except the stopwatch chunk is commented out
so you only do one pixel per frame then since you yield return null every time that method is called
sec
private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
{
if (x < 0 || x >= maxX || y < 0 || y >= maxY)
{
yield break;
}
if (Map.instance.GetBiome(x, y) == (Biome)_type)
{
yield break;
}
Map.instance.SetBiome(x, y, (Biome)_type);
UpdateTile(x,y);
// Recursively fill neighboring pixels
yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
}```
The yield null part was removed too, everything in that block
What does "yield return" do exactly? I think understanding that would help a lot
so you want yield till end of an extended amount of frames?
Yeh basically, I want it to fill as many in 0.2 seconds as it can
yield return returns a value from the iterator
Right now it seems to yield on every single tile, from my recordings
stopwatch usually accurate but I hear coroutines may not
so unless you do it per frame basis, I don't think you may get the exact times you want
can anyone come to #💻┃unity-talk and fix my problem if want to?
does yield break wait a frame in this instance @timber tide, since it will be yield breaking out of one of the yield returns. Or does unity only wait a frame when its null?
but instead of using stopwatch, just try wait for seconds for the heck of it
This is what I am thinking too... Because when it jumps to the next tile, it'll always break in 1 direction because it'll break on the tile it just came from
And I don't yield anywhere else
I don't fully understand what you mean here Mao sorry
mao I think the problem is that it's too slow not that it should be slower
Dont crosspost #📖┃code-of-conduct
^ Yeh basically, because it does 1 tile every frame, it's being bottlenecked by needing to run all the Unity / renderer stuff every frame
So my tile generation is locked to my FPS (basically)
ok
what's your fps?
sec, I'd need to add some code for that
right, then you need to do it by frame time then
why?
Yeh exactly, for this example we could have the coroutine capped to 1 second
there's a stats button you can click in the game view
just send a screenshot of that
Yeh my bad, see I generally make tools to create game stuff inside play mode 😅 So I forgot about the unity stats
sec
so yeh, 120 fps
with dips when it hits the end of a line
So the coroutine is yielding 120 times per second
float waitTime = 0.20f;
float elapsedTime = 0f;
IEnumerator YourCoroutine(float waitTime)
{
while (elapsedTime < waitTime)
{
elapsedTime += Time.deltaTime; //whoops how did I miss this
yield return null;
}
}```
Basically just an update loop ;p
oh, but you may want to wait after you do a line then do the wait?
Not sure of the requirements
Would I need 2 coroutines? Seeing as my current coroutine is a recursive loop?
This looks correct
based on this code I'm not sure why it would be yielding per frame, something else must be going on. It honestly looks too slow to be yielding 120 times per second, but I can't verify that. Perhaps yield break in this particular instance causes the coroutine to wait a frame because of its use, but I wouldn't count on that. It Could be due to the recursive nature.
I think you need a bool that says once you're done -> then wait
I don't want anything fancy, this isn't to have a visual look at the world rendering, I want it to be done as quick as possible, but it was giving me a stack overflow issue if it wasn't a coroutine
I mean it doesn't look like it's yielding 120 times but correct me if I am wrong... If it wasn't yielding then it would hold the frame and that would make the FPS lower, so if I have 120 FPS it means that it must have yielded 120 fps because that is running every frame
well I can't verify that it's running 120 FPS unless you debug that, but it makes sense that it wouldn't have a high FPS if it wasn't ever waiting a frame.
I'm just not sure how I get my recursive loop into a while...
It says that in the stats screen
i meant yielding once per frame sorry
Well it has to yield once per frame? Otherwise it'd not be running?
That's how coroutines work no?
i don't know, as far as I know it shouldn't yield once per frame unless yield return null is called.
Don't coroutines naturally block a frame until it either yields or finishes?
Assuming they'd want to operate as much as possible but only for a maximum elapsed timecs float maxElapsedTime = 0.20f; float elapsedTime = 0f; IEnumerator YourCoroutine() { while(!done) { while(elapsedTime < maxElapsedTime) { //Do stuff elapsedTime = ... } yield return null; } }
coroutines are just update loops, but they allow you to pause execution
and return to where it has left off sometime later
Yeh exactly, so if I have 120fps then it means the coroutines has to be pausing 120 timer otherwise it'd lock the frame?
Coroutines are just code eexecuting, you can execute as much code as you want in one frame. Yield return null tells it to wait a frame. You can yield return other things that tell it to wait for other things too, like yield return new WaitForEndOfFrame() and yield return new WaitForSeconds(2f).
what I'm saying is you don't have a yield return null so I'm unsure as to why it's waiting a frame to continue the work.
So the thing is, that coroutine is exactly just the code I showed you... Other than the 1 time it's called
Yeh I don't quite understand that too :l it has to be the break right? That's the only yield I have
only thing that will lock the frames is if you don't return in a while ;p
its a recursive function, it should lock the frames as long as it keeps calling itself
Yeh that's my point, so the FPS is directly tied to that...
Also with it being recusive... I duno how I'd change it to be a while loop
Not sure how I'd write that though...
Seeing as it's independent and just kinda chains on itself to check all blocks, I feel that would be a pain to keep track of in normal code
How do I keep track of what blocks need to be checked?
It seems complicated
Oh also... This gave me a stack overflow and it crashed my game
That's why I made it a coroutine in the first place
Sorry, I initially misunderstood your question
The game would freeze for like 8 seconds and then error
so at what point is the recursion done such that you can get to the next frame
Erm... instead of calling them like
" yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left"
Should I be calling them as their own coroutines?
Or would that cause issues? I duno
I feel like that'd be bad hehe
I guess it waits a frame because enumerators return null once they're past their end, so it returns null once when you break? You might be able to make it faster, just remove the yield breaks and instead check the inverse of what you want and put the recersive functions inside that. So maybe try:
private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
{
if (!(x < 0 || x >= maxX || y < 0 || y >= maxY)
&& Map.instance.GetBiome(x, y) != (Biome)_type)
{
Map.instance.SetBiome(x, y, (Biome)_type);
UpdateTile(x,y);
// Recursively fill neighboring pixels
yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
}
}
Ohhh does it return null by default? Should I have a return break at the end????
yield break*
Rider says it breaks by default, it doesn't return null
I don't think you need yield break like this, but perhaps yield break is causing the enumerator to return null to the coroutine, which causes it to wait a frame.
Also I do like the code change in general, a lot cleaner
I will give that a go
No, still acts the same
I don't get it...
There's no way that waits frames
I feel like you should figure out how to get it to work in update because stackoverflow usually implies it's not exiting at all.
how does stackoverflow usually imply it doesn't exist?
I assumed because it was running just such a large amount of times that it just filled up the stackoverflow before it had finished. So Unity just assumed it wouldn't finish
I think stackoverflow is more that it just didn't exit soon enough, not that it doesn't exit at all
idk, I've done some large freaking binary trees in c# that took minutes and never really gotten that error
Did it have a massive recursive stack? Because the stack will be tracking each one of those calls
it could be caused by something they're doing in one of those other functions if they're recursively calling this forever and creating new structs, since those won't leave the stack if it's just created in a local function like that.
haven't tried anyting too heavy computated with unity though so maybe there's more to it
I mean the code itself is poorly optimised, I want to work on that next but that doesn't solve the problem of why this keeps... wait
Would it matter what my function call returns?
UpdateTile is void... SetBiome is void too
nvm
For exmaple, I believe this code:
List<Vector3> list = new();
while(true)
{
list.Add(new Vector3(0, 0, 0));
}
}
```could potentially cause a stack overflow, if the vectors don't move to the heap. I'm not sure if they would or not in this case. So I think it depends on what's happening in those other functions as to why there's a stack overflow exception.
I think it just doesn't like recusive function calls that go into the 1000's
Correct, happens when methods call themselves over and over, without an exit condition
Yeh
SPR2, by any chance... can you see why this coroutine keeps constantly yielding and waiting for the next frame?
private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
{
if (!(x < 0 || x >= maxX || y < 0 || y >= maxY)
&& Map.instance.GetBiome(x, y) != (Biome)_type)
{
Map.instance.SetBiome(x, y, (Biome)_type);
UpdateTile(x,y);
// Recursively fill neighboring pixels
yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
}
}```
I have this video to show what i mean
can you put a debug log in there, and log the current frame (Time.frameCount, inside the if statement), and put the console on collapse mode, so you can see how many times it's being called per frame?
Interesting
I remember when I left a debug log in this system by accident when debugging something and I ended up with Unitys debug taking up 15gb of ram lol
Ah, ok so theres a 1 MB limit to recursive calls apparently, but there's ways around it in c#
I don't think that's the proper solution in this instance
it would require using Thread class to get around which probably not a good idea anyway with unity
Yeh that does sound like a wonky work around haha
so you'll need to spread out the calls through the frames it seems
or do partial recursion
I guess, I don't see your debug log code. But if it's just inside that if statement, then yes. So i'm very unsure as to why that is yielding a frame, I don't think this should yield a frame it should just forever call this method. Perhaps unity's coroutine system has some sort of recursion limit that's causing this? It shouldn't be yielding every frame like that.
private IEnumerator FillWithinPaintedAreaCoroutine(int x, int y, int maxX, int maxY)
{
if (!(x < 0 || x >= maxX || y < 0 || y >= maxY)
&& Map.instance.GetBiome(x, y) != (Biome)_type)
{
Debug.Log($"Valid Tile : {Time.frameCount}");
Map.instance.SetBiome(x, y, (Biome)_type);
UpdateTile(x,y);
// Recursively fill neighboring pixels
yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY); // up
yield return FillWithinPaintedAreaCoroutine(x, y - 1, maxX, maxY); // down
yield return FillWithinPaintedAreaCoroutine(x + 1, y, maxX, maxY); // Right
yield return FillWithinPaintedAreaCoroutine(x - 1, y, maxX, maxY); // left
}
}```
It's just inside the if
In the video you'll notice when it gets to the end of a line the FPS drops a lot from like 120 to 30 or something
That must be where it called 17 times in 1 frame
And then it cycles down again, so yeh it is yielding each frame while generating tiles
It has to be "yield return FillWithinPaintedAreaCoroutine(x, y + 1, maxX, maxY);" this then?
But I don't understand why the end one runs so many times...
Sorry guys q.q
And I appreciate the help
no that wouldn't do it. It has to be because it's recursive. Any recursive algorithm can be implemented without recursion.
How would I convert it to a while loop? 
Store work in a data container then to next calls on them
Recursive IEnumerator calls seems to be no beuno
I avoid recursion when I can haha
Guys how about I move the tile set stuff into a new function that isn't IEnumerator
Basically split the function in half and call that instead
I would maybe use a HashSet to keep track of what coordinates you've visited:
IEnumerator Start() {
HashSet<(int x, int y)> visited = new HashSet();
int loopWaitCount = 0;
while(someCondition)
{
if(!visited.Contains((x, y)) /*&& conditions*/)
{
// do stuff
visited.Add(x, y);
if(++loopWaitCount >= 60)
{
loopWaitCount = 0;
yield return null;
}
}
}
}
@mystic steeple maybe something like that?
Yeh, I've just developed a bit of brain fog
since you mentioned keeping track of what you've visited before would be hard, this does that
Hey guys! working on my mutliplayer game and i'm wondering if there is some sort of way i can keep my player in a specific "square" or area in the game and not move beyond it.
my player uses a rigidbody and box collider
Depends on your movement but there are 2 ways.
- in your movement code check if the new position would be out of bounds and just... Don't run the move code if so
- boxcolliders
how do i do 1?
thats my question
You're moving using physics?
yes
Okay I'm not too familiar with physics... but it depends on how your out of bounds works? You can either have a box collider in the areas you're not allowed in (This is better for more advanced shapes, you can have a trigger collider in front of your player and if it enters out of bounds, you can set velocity to 0?
or if it's more primitive shapes like a cube exclusively, you could also just get your position, add like +1 to the direction you want to move and see if that is out of bounds by just doing a simple if comparison
hm, ill try a box collider.
Just remember to be careful not to get your character stuck.. Either
- Make sure a player can rotate when their movement would be out of bounds (So you can move to a valid rotation)
- Have your trigger box collider independent of the player, so it checks where you want to go, rather than where you are facing. Depending on your rotation be careful that they can't jimmy through out of bounds by rotating though
maybe to make it simple
Also sorry, I'm going to just ponder the general concept and see what I can come up with using your suggestion, I have an idea but my brain is all cloudy so going to leave it a minute but I'll let you know if I get it fixed 🙂 Thanks for all the help btw, I appreciate it
ill put box collider walls
Yeh and then have a trigger in front of your player that doesn't allow movement while in a wall but still allows rotation
if you stick to unity's methods of movement and collision, it's less code you need to write
network transforms do a lot of work for you
Bro I duno why I didn't just think about using the collider to block movement haha
I just default to mine because it stops walking animations into walls 😅
But yeh you could just ignore me completely and just only have the box collider walls 
benefit to my approach is that you can just stop animations if they can't walk there
figured out a solution
since my games a ball game
only the ball can pass through these specific barriers now
everything else including players will not be able to pass through walls
need help with audio, i want to add a pop sound when the ball is destroyed
which script i do create and where do i attatch it, i tried some methods but not working as i wanted it to be
Perhaps you want a reference to an audio clip and audio source. Then in the on destroy method of a monobehaviour, call audioSource.PlayOneShot(audioVlip).
Just make sure that you dont destroy the audiosource too
Can also use AudioSource.PlayClipAtPoint which spawns a separate temporary audisource object
when i did that the ball mechanism becomes broken, i need some method to have audio in different script
!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 UnityEngine;
public class Audio_ball_pop : MonoBehaviour
{
public static AudioSource SRC;
public static AudioClip popAudio;
public bool isPlayed;
void Start()
{
isPlayed=true;
}
void FixedUpdate()
{
if(Ball_mechanism.canPlayAudio==true&&isPlayed==false)
{
SRC.clip = popAudio;
SRC.Play();
Debug.Log("i played audio");
isPlayed=true;
Invoke("delayedPlay",2f);
}
}
public void delayedPlay ()
{
isPlayed=false;
Debug.Log("i SET the isPlayed to false");
}
}
i tried using this, it worked but i cant stop it after once its started.
the invoke in 1st code doesnt work for some reason
yeah i still can't solve it ._.
What exactly is Ballstart and Ballend? And where is that instance of Ball_mechanism located, what is it attached to?
ball start and ball end is 2 gameobject 2ball start combine makes a ballend
ball mechanism is attatched to 9 different balls
So when two balls collide, they are both destroyed and Ballend takes their place, right?
yes
The first one being collision.gameObject (the other ball) and the second one being Ballstart (ball with this script attached)?
let me explain
how can i start a coroutine from another script
i have 9 balls each balls has this script attached, when a same ball collide(1ball collide with 1ball makes a different 2ball)
and its working pefectly unless i add audio in between the script
Does anybody have any solution for this ?
For example, by calling a method which starts a coroutine
oh thats a good idea
thanks
i need some alternative to add a pop audio when this ball is destroyed
I've read online it's due to the dropdown having its own inspector window.
https://gamedev.stackexchange.com/questions/189856/unity-inspector-not-showing-variables-of-custom-component-that-inherits-from-a-b
But I don't know how to override this window
So, Ballstart is a reference to the same GameObject where the instance of Ball_mechanism component receiving the OnCollisionEnter2D call is located, right?
Basically, I just want my new dropdown editor to use the old dropdown editor and jsut add a toggle in it.
yes
But I can't figure out how to create a component window
Then, wouldn't it be easier and more intuitive to just use the gameObject property instead of referencing it? Unless the component is on a child GameObject of the whole ball
https://docs.unity3d.com/Manual/UIE-HowTo-CreateCustomInspector.html
Ok... Seems like it's a hassle lol. I'll just use the debug mode to enable my boolean. Too badd..
And with now knowing that, the delayed Invoke doesn't work because you destroy the component responsible for the Invoke
so what can i do, where do i put the script, and will the collision still works?
Basically, instead of using some weird static bools here, make yourself a BallManager
Give me a few seconds, I'll give you an example of what you could do
OK nevermind again. Using [CustomEditor(typeof(Dropdown), true)] allowed me to create a new custom editor for my new dropdown which inherits from the parent dropdown and adds my new toggle. Great
Nevermind x3 lol The new inspector does display everything but as a simple list of elements unlike the original dropdown inspector. Too bad :/
Nevermind x4, I've just went ahead and copy/pasted DropdownEditor in the packages list and added my toggle lol. That worked this time.
Could be, more or less, done like this
// Ball.cs file
public class Ball : MonoBehaviour
{
// No need for any of these to be public and exposed to other scripts, only needs to be accessible via this script and the inspector.
// If the Ball script is located somewhere under the whole ball object use _root, otherwise just use the gameObject property inherited from MonoBehaviour.
[SerializeField] private GameObject _root;
[SerializeField] private GameObject _biggerBallPrefab;
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(_root);
Destroy(collision.gameObject);
Vector3 spawnPos = collision.gameObject.transform.position;
Instantiate(_biggerBallPrefab, spawnPos, Quaternion.identity);
BallManager.OnBallMerged();
}
}
// BallManager.cs file
public class BallManager
{
private static BallManager _Instance;
[SerializeField] private AudioSource _audioSource;
private int _score;
private void Awake()
{
_Instance = this;
}
public static void OnBallMerged()
{
if (_Instance != null)
{
_Instance.OnBallMerged_Implementation();
}
}
private void OnBallMerged_Implementation()
{
// Now increase score here, play a sound, call Invoke, etc
}
}
so this script handels all balls at once or do i need to attach it to every ball
You call a static method, there isn't anything to attach
Just make one BallManager, attach any audio sources, clips and other stuff you may want to it and that's it
IEnumerator TypeText()
{
float timer = 0;
float interval = 1 / charactersPerSecond;
string textBuffer = null;
char[] characters = line.ToCharArray();
int i = 0;
while (i < characters.Length)
{
if (timer < Time.deltaTime)
{
textBuffer += characters[i];
gameObject.GetComponentInChildren<Text>().text = textBuffer;
timer += interval;
i++;
}
else
{
timer -= Time.deltaTime;
yield return null;
}
}
}
can someone explain what this code does? what is textBuffer and timer?
You could also just call base.OnInspectorGUI() to draw the parent class isnpector. Draw your custom stuff before or after that
public void AddWeaponFromCollection(string weaponName)
{
foreach (var child in weapons)
{
print("Found: " + child.name + "in Weapons. We are attempting to add: ' " + weaponName + "'.");
if (child.name == weaponName + "(Clone)")
return;
}
foreach (var weaponData in gunCollection.allGuns)
{
if (weaponData.gunName == weaponName)
{
GameObject newWeapon = Instantiate(weaponData.gunPrefab, transform);
weapons.Add(newWeapon);
newWeapon.SetActive(false);
break;
}
}
}
``` My guns get instantiated, but that 'print' never goes through??
You could also use events or other stuff, but I don't want to mess with your head more than that
weapons List is not empty
it takes 2 gameobjects _root and _biggerBallPrefab
how does this works for all the 9 balls?
real question: is chatgpt reliable for coding
_root and _biggerBallPrefab is the same as your previous Ballstart and Ballend, but with more understandable names
Yes if you can solve it from there
when its wrong (a lot)
i just want it to explain stuff for me, not to generate code
Why that over videos or docs/
Print the count of weapons before the for loop
But, if you don't want to attach the prefabs everywhere, you could just attach them to the BallManager, pass your current ball size/tag into OnBallMerged alongside with the position, and let the manager create a new ball
Unreliable. Dont use it for learning please
okay then
I just reimported my unity project 😭 ?
Nothing prints?
Then this function is not running
why is my text lagging
How are you showing the letters? Coroutine?
did chat gpt write tht
Maybe it is getting called more than once
nope
oh wait i think i know the issue
its connected to a player input and maybe the input is running 3 times
because it happened to me before
Yeah
BEFORE
public void OnInteract()
{
if (isInteractable)
{
dialogueBox.GetComponent<DialogueBox>().StartDialogue(dialogue);
}
}
AFTER
public void OnInteract(InputAction.CallbackContext context)
{
if (context.performed)
{
if (isInteractable)
{
dialogueBox.GetComponent<DialogueBox>().StartDialogue(dialogue);
}
}
}
when i changed it to after it didnt work
anyone know why
I thought that should work
Theres also context.started, maybe thats worth a try
Also there is #🖱️┃input-system
oh ok thanks
Put it in a paste site instead: !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.
yo thank you! that worked
what does hatebin do
check it out
i jst did
Lol, nice
https://hatebin.com/fyuglbaiou whars wrong with this script
You tell us 🤔
1 fgp should be spawned every 3 seconds but it spawns 2 fgps every 3 seconds in the same place and every 3 second 2 fgps spawn on the fgps
and i keep getting the fgpPrefab is not assigned in the FGPSpawnerWithGap script!
UnityEngine.Debug:LogError (object)
FGPSpawnerWithGap:Start () (at Assets/scripts/FGPSpawnerWithGap.cs:19)
error
just checking if u dragged in the prefab into the inspector
i did
i seee
well in terms of this, you're running the Instantiate method twice in SpawnFGPs, which will spawn them twice every time it's called (which is once every 3 seconds). if you want just one to spawn, you should only call it once
unless im misunderstanding something
Instantiate(fgpPrefab, new Vector3(transform.position.x, bottomFGPPosition, 0), Quaternion.identity);```
oh i see nvm
u want one on each spot
Maybe you have many FGP spawners in the scene
oh true
@queen adder type t:fgpspawnerwithgap in your scene hierarchy search
It will search by that type
its only in
oh wait
How about when playing? Is something spawning more of these?
so this has FGP on it. by any chance is it spawning itself
if it's spawning itself at runtime, then it wont be assigned in inspector
the fgp script is the movement of fgps
Does fgp have the spawner script on it?
nope only the fgpspawn game object
Hi, dumb dumb here. How does friction work? Like, I had it so that it was just an inverse force against the velocity so that if the player lets go of the controls, it applies the inverse until it reaches zero
Which is been working fine so far, until my character had to go through a loop, and I think when the character starts falling downwards due to gravity, if the gravity isn't strong enough, the friction cancels out the gravity and my character starts accelerating through the loop.
i dont think thats how friction is supposed to work
should I just disable friction above like 90 degrees?
id say go in playmode, and play until the error happens, THEN check all the objects with the script (to see which ones dont have it assigned)
the logerror is on start, and nothing is affecting the reference
i already downloaded the virus
yeah at the end of that video, id pause the editor (next to play button) and check objects with the script
how? (i use obs btw)
u can legit just go in file explorer and change the extension
itll convert
if u dont see extensions, go file explorer -> view -> file name extensions
(theres also an obs output setting to just output mp4)
discord only gives me the download option to view stuff so idk if its visible for yall or if yall have to download
osmal means turn the video into mp4 then upload to discord again
this SHOULD work
so the fgps that are being spawned also have the spawner script on them
and the spawner script is running the spawn logic
is that intended?
is this not the right way to use a variable with a scriptable object
nope
can u send a screenshot of CounterVariable too
The fgp's do have the spawner script on them though. Exactly what I was asking, but you said no
im gonna use counter because ill need to reference it in different scripts
i mean i think this is fine? its getting the counter variable from the instance of the scriptable object
it doesnt seem to wanna do calculations or assign the variable maybe
i thought you were talking about this fgp not the clones
Yep seems fine to me
those clones have all the same components as the original prefab
so theyll have spawners as well
Show the inspector of the fgp prefab
i get the text on screen but i dont get a counter
Okay so other than me messing up my logic somewhere and creating a pretty bad leak, I think I've figured out how to fix my problem
My coroutine works
Definitely yes, why would you want it there
check the object LogicScript is on. u might need to drag in an instance of the CounterVariable scriptable object
Looks like you didn't assign CounterScript in the inspector, but are trying to use it
huh
Ok it's assigned here, but do you have another LogicScript in the scene perhaps?
Type t:logicscript in the hierarchy search of the scene v iew
by the way, if youre using a ScriptableObject for kinda "global" variable, it might be easier to make a static class for it
yea but that wont really be global will it?
how would i have the information the same on all types of it
Do you need to assign different CounterVariables for different objects?
no just the one
ya that sounds like a static situation to me
i see
wdym by this
like what osmal said
wait yea
I mean if you needed different versions of CounterVariables, then ScriptableObject would make sense. But you dont
that will be 5 whenever ANYTHING references it
oh
ScriptableObjects are good when u want instances of something without having to put them on objects
yea
i thought you could only use static variables once per script that was my mistake
ScriptableObjects are also handy as a sort of 'config'/'settings' asset. But as it's the same for each object, you could reference it in a manager (singleton) class instead of each object
this is more of a c# question but does .net optimise divisions? like for example variable / 4 gets converted to variable * 0.25
yea ill keep that in mind 😅
does this happen in il2cpp?
wait how is it that useful if i have to create a variable to use the scriptable object variable
is it because it doesnt need sterializewefewgf?
Mostly that yeah
It's not a big deal tbh
oh amazing
i sterilize my scriptableobjects
Just saying that SO's have their place when it comes to stuff like this
what about putting ur hand on the stove as a kid...
no i still do that
ah
@timber tide @grave frost Okay I got it working 🙂 Your suggestions and advise helped me come up with a new system! Thankies
It's a little bit faster now haha
hi, i want to make 3d horror game using users1 long tutorial, but i have some issues.. do you think someone could help me a bit.. i would be really happy
i made a method which sets a bool true or false
for the animation events
but it doesnt show up on the list
why
its not private
I duno the commands in here
!ask
!justask
Maybe this server doesn't have it...
Your best bet is to ask your question rather than asking if you can ask.
if someone knows how to help with the problem, they'll help! But people are less likely to help if they don't know the problem... Because nobody wants to walk into an unknown problem that they might not be familiar with
0 issues but there arent calculations in the output
Is the method ever called?
when it updates
unless i need the script to be somewhere
not to my small knowledge
is it monobehaviour
yea
I'm guessing you're not getting the yo outputs?
Start() and Update() are methods on monobehaviour that are called on an object in the scene
So.. do you have anything that calls the money method?
so yeah Start() and Update() will only be called if an object with that script is in the scene
So the money method doesn't ever run then?
no😭
Well if you want it to run, you'll need to call it
how do i get another script in here
wait no
thats a script
oops
wait no that will do its an onbject
Class : MonoBehaviour
means it's a type of monobehaviour, it inherits it. monobehaviour is what allows scripts to be put onto GameObjects
they act as components
so youd do add component
You have 2 on it now, btw you can just drag scripts onto objects
yea if u want 2 of the same class on one object
gameObject.AddComponent<ScriptName>() to do it through code
yea i come from roblox so im used to everything being sub optimal
im getting there though!😎
Well the foundation and basics are transferable, so you still have a leg up
Just gotta learn the ins and outs of the software really
So yeh just remember that if it derives from Monobehaviour, it needs to exist inside your scene
ill attempt to remember
Any idea why I'm getting an object instance error when I'm defining it and referencing its field from another class?
At a guess, the gameobject already has a CharacterControllor attached
Any particular reason why you're adding the component during runtime and not from the inspector?
You probably typoed AddComponent instead of GetComponent
Me and a friend are new to making games and are trying to use Version Control to work on the project together.
We've managed to send/share assets, is there a way to share the scene too?
Like I've created the player movement, but when we use VSC it only shares the scrips etc., not the small level including the player I've already build.
are u using github
I am not
which version control
Should I?
yerp
Great
basically version control tracks which files to share, so i guess with the one u were using, it wasn't tracking wherever the scenes were being saved
with git, that stuff is handled with t he .gitignore file which u can configure in like notepad
u just add the paths it should IGNORE
and not share
like editor settings, big build files,etc
Ahh ok
github will even have a template for u
I was using the build in Version Control from Unity DevOps
oh yea idk anything about that
I'll take a look at github, thanks for the advise
Be wary of merging scene objects and certain resources https://forum.unity.com/threads/github-scene-merging.1034548/
with github u get a nice dropdown with a gitignore template so when it makes the repository itll add the gitignore
yea the one thing about sharing scenes, making ONE CHANGE to the scene will count as a change to the whole thing
so if u both make even a single change, it will likely conflict
Ahh ok
while github desktop makes merge conflicts less scary, it's still nicer to just avoid them altogether
We're mostly working on the project at different times, or on call so that should be ok
Hey, how do I make the code check if a gameobjects position isn't equal to a certain y value
if (gameObject.transform.position.y != certainOrdinate)
aha, thank you
not a good idea btw, never check floats for equality
Yeah, use Mathf.Approximately
yea do like < 0.01f or mathf.approx
Forgot about it
alrighty
if (!Mathf.Approximately(gameObject.transform.position.y, certainOrdinate))
the majority of people use the built-in version control "Plastic SCM"
no they don't
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Is it possible to add a listener in the first position to make sure this method is called first ?
What position? Which method?
If you want ordered event handling i recommend creating your own system where you place delegates in a list and execute them by iterating over the list. This way you can order the list however you want.
Someone have any tutorial to make Shine effect on text?
that's VCS, btw. version control software
distinct from VSC, visual studio code
hey, i have this code and the effect spawns at 0,0 instead of bulletOrigin's position, anyone have an idea why?
you are setting the prefab to bulletOrigin instead of where its hit from your "out hit"
Are you sure 0,0 isn't bulletOrigin's position?
Have you logged bulletOrigin.position yet?
my bad on the naming, but its the muzzleflash fx
Shouldn't you be spawning that unrelated to a raycast?
yea that's the transform of the barrel's end
Have oyu logged its position yet
Maybe you referenced the wrong thing
valid point, but currently im only firing if the raycast hits something
This is not Debug.Log
Just because your variable is named bulletOrigin doesn't mean it's referring to that pictured object
tha's the log
What does this Position at log print?
well, its in the floor instead of barrel's end
looks like not 0
Based on your log, your issue has nothing to do with this code, since the log is showing clearly it's not spawning at 0,0
So the problem is elsewhere
perhaps other code, or perhaps some setting in your VFX
perhaps an animator or something
i'll check those stuff again
okay, so the effect itself is set somewhere to 0,0
even if i move the effect gameobject, it stays at 0,0
im checking why
Is this a VFX Graph? or Particle System?
vfx graph
Ok yeah something is wrong inside the graph then
maybe it's using world space positions instead of local
yep, i created a new one and it moves
it indeed was, fixed. ty everyone 🙂
Guys, my code returns an error when the bird dies. But it doesn;t return the error when the bird dies from the pipe heads.
So basically there's an audioSource returning this error
What are the differences between the two deaths?
Yeah looks like you're trying to play the source and it has no clip assigned
The other deaths trigger when player triggers other parts of the pipe or moves out of scene view
How do the deaths differ?
While the pipe head death occurs when player collides witht he head of th pipe
There's no difference
I'm assuming you're doing extra stuff that are different between the two death events
I just added a sound event
I mean a sound playing but it is there in both death events
Because whenever player dies a GameOver function is triggered which also plays that sound
Show some code: bird death with and without pipe
it happens even in pipe. All the body of pipe except the head
I thought you had said there isn't an error if the bird died by pipes?
#💻┃code-beginner message
I said the pipe head
not the whole pipe
The console says that the error is on the last line of code
AudioGameOver.Play()
Where do you call Game Over?
In other scripts whenever player dies
Here
I'm assuming all deaths call Game Over but something likely is different between the one that has the error thrown and the one that doesn't - could be a state or whatever.
There are only 2 times when the function is triggered.
- The playeer collides with pipe
- The player goes beyond max and least height
In the second case it returns error. In the first case it returns error at when the bird hits the pipe body
and doesn't return the error when bird hits the pipe head
The only difference I can immediately see is that one occurs during the physics frame (fixed update) and the other during the regular frame (update)
ohhh that might have ima try to fixedUpdate this one too
Can you show the stack trace for the error?
That didn;t work
Is there more to the stack trace? Anything cutout from below?
nope
There is also this
Hmmm normally they'd tell which function had called game over and whatnot
right
Can you show your bird script? How to post !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.
Click a link, paste your text, click the save button somewhere on the site, copy and paste the url here
So that ought to be an Update method and not Fixed Update
You cannot query input correctly in Fixed Update
BUT even in update it returns the error
the error is in LogicScript, not BirdScript
ohh
So how can it be fixed?
https://gdl.space/icumowatob.cs , the LogicScript
That isn't the point. You should not acquire input in the Fixed Update method. Other than that, it's stating that your source for your audio player is null or has become null.
The error isn't caused by reading input in FixedUpdate, but it's definitely something you should change
I wasn't talking to you.
i think groosky was mixing up the exception with your comment about reading input in the wrong place
I filled it up
GetKeyDown returns true for only one frame. FixedUpdate runs 50 times per second by default, so you can completely miss the input.
Now I did Update
It still gives the same error
It was originally Update but they had changed it to fixed update (not sure why) because I had mentioned that the two calls were mainly different with regards to when they were called #💻┃code-beginner message
That's expected. Now, before the audio source plays add this linecs Debug.Log($"Click here to see the audio source light up", AudioGameOver);
oh ok
Output when code doesn't run
Output when code runs
Which object lit up in the scene?
hey, i have another question.
I don't know why but my player shoots from 2 locations.
i specified the Ray to come out of the camera on the player, but it seems that there are 2 cameras, and although i see 2 camera gizmos, i can't find the second one
When the code ran, then it was the bird. When it returned error, there was none.
An object in the scene should flash yellow if the object hasn't been destroyed or the scene hasn't changed etc
it sounds like the context object is missing when the error happens
I shall reload the object in the function?
With the getComponent thing'
What? 🤔
What happened to the object?
think about why the object might have suddenly disappeared...
Bird glows when game over triggers on colliding with the pipe head. Else nothing glows
I'm only aware of you setting the game over screen active and playing the audio. Are you destroying or doing something to the bird?
On the other events when the function triggers nothing flashes
nope
I am only disabling it's movement
well, here's something interesting to me...
AudioGameOver = GameObject.FindGameObjectWithTag("Bird").GetComponent<AudioSource>();
This runs in addScore
I'm going to assume that they all throw the error and that it not triggering for the pipe heads is simply undefined behavior (50/50). Can you post an image of the audio source component?
But what if you've never gained any score?
searching for AudioGameOver in addScore doesn't make sense.
You don't use it there.
Are the pipes and bird present from the very beginning? If so, consider referencing through the inspector rather than searching the hierarchy.
The pipes are probably spawning in over time
I'd just move the audio off the pipes entirely!
and off the bird, too
why not making an audio manager?
or just slap some audio sources on the same object as LogicScript and call it a day
This has me thinking that the score might possibly be evaluated when they are near the pipe heads (between the pipes) thus not causing an issue on death - audio source has been referenced by then.
yeah
Code that takes advantage of a coincidence (you usually get points before you lose the game) can fail randomly like this
In a 2D game, does a Raycast2D hit a collider that is higher or lower in the z axis?
Move the audio and audio game over assignment statements into a Start method. They really ought to initialize those fields on start rather than when you acquire score.
You can configure this with a ContactFilter2D
In 3d, it'd hit the first collider. Assuming you've got the default orientation, moving towards the camera should decrease in the z axis - implying that it'll hit the object nearest to the camera (assuming you're shooting the ray from the camera).
public ContactFilter2D myFilter;
I have a raycast that is checking if a tile with a collider in the game has a "Walkable" tag, but i also have an object on top of it(closer to the camera) with a collider tagged "Interactable". so it would hit the interactable tagged object instead of the walkable
Should probably consider filtering by layers and whatnot rather than just accepting the nearest.
Ye
They are already in statt
Nvm my bad they aren't
Thanks for the help I'll apply this when I get back to my PC
https://gdl.space/eqehufivaw.coffeescript
i have some code here that checks if the collider has a specific component attached set to null, but im not sure if its working the way i want it to. if the hit object has the "weaponName" assigned(meaning its a weapon) it works fine, but if it has the other two in the else if's it doesnt work and gives a null reference exception. im pretty sure it means that it doesnt find a "weaponName" for the first check because it doesnt have one, but i thought that that would just mean its null and should just go to the next else if statement
Maybe log what you hit?
Make sure to include a comma and the component/gameobject to have it become highlighted in the scene.
oops
RaycastHit2D hit = Physics2D.Raycast(raycastStart, target, 1);
Debug.Log("Hit object:" + hit);
hit is not a unity object
you can't use it as the context
on the other hand, hit.collider is a unity object
After verifying that you've hit something, check what you hit.
It should have a property to access what you hit.
it does hit the Chest, which is what im trying to test
but it doesnt give a debug log saying "Collectible is a chest!" meaning it stops at this part of the code:
" if (hit.collider.GetComponent<Collectible>().Weapon.WeaponName != null)"
Likely you've got an nre there
im pretty sure this statement doesnt work
yeah
i mean to check if it even has a component like that
An error will stop the execution of the remaining code
but if it doesnt to move on
i dont mean to check if that component has a value of null, i just want to check if the hit.collider has that component
how do i do that
sounds like you want TryGetComponent
if (something.TryGetComponent(out Collectible collectible)) {
// collectible is non-null in here
}
// collectible might be null out here
You need to verify if it's got the collectible component first before attempting to access the weapon or weapon name
if its gotten this far in the code it will always have the collectible component
well at least right now
but thats good for the future i will change it
not every interactable will be a collectible
How do i make a Vector that is only for direction with a custom length that stays the same no mater how long the original vector was?
Normalize it and multiply it by some scalar
dosent work
you can normalize it
That was quite fast, maybe you ought to tell us what you've already tried.
Or why you feel it doesn't work or wouldn't work etc
i normalized the vector and multiplied it by 4 and its still different depending on how long the original vector is
So the Collectible will always have one of three scriptable objects as of right now. i just need an if statement that checks which one it has, because it will never have more than one
When you normalize it, it will have a length of 1. Multiplying it by 4 will have it always be a length of 4 regardless of the original direction.
i have changed literally nothing and now it works, thx i guess
Im gonna move all the code out of where it was previously into a new void to make it easier to read, does this work?
CheckInteractable(hit);
private void CheckInteractable(RaycastHit2D hit);
Not sure, maybe - beauty is in the eyes of the beholder.
it seems to work, but i still need to figure out how to do an if statement that checks correctly if the component has a weapon, chest, or accessory
why cant i set rotation to a vector?
because transform.rotation is not a Vector3
Error should have told you that it's a Quaternion
consider transform.eulerAngles (and maybe show us what you're actually doing here)
Quaternion does have a static Euler method though - to create Quaternions using euler values.
im trying to make a bullet point in the direction its moving
transform.rotation = Quaternion.Euler(...);```
ah, then you'll be very interested in...
anyone know the best way to achieve a servo type motion using hinge joints?
transform.rotation = Quaternion.LookRotation(transform.forward, Vector3.up);
im not very versed on rotations w/ rigidbodies
unless this is a 2D game, in which it's a bit different
it is
got a little robot all physics objects and imma try to put em together and make a controller for the leg joints (first)
assuming that the bullet is flying in its "up" direction
w/ limits and whatnot
the green arrow when you have it selected
(had this backward)
Quaternion.LookRotation is used to compute a rotation that looks in one direction with a second vector as the "up" direction
In 2D, the "forward" direction is pointing into the screen
So we ask for a rotation that looks into the screen (Vector3.forward) and with the appropriate "up" direction
also, I just realized that using transform.up is not very useful here lol
use the direction the bullet is flying
the code currently just makes the bullet point in the direction the bullet is pointing!
thats what im trying to figur out
i dont know how to get the direction the bullet is flying in
well, is the bullet moving at all?
yes
yes
you can get the velocity from that component
It's still not working
only 1 change
📃 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.
you're trying to find a pipe the moment the game starts
no pipe exists
why can't you just put these audio sources somewhere else?
like on the same object as the LogicScript
Oh wait I can actually do that
thx
and then, you can just directly reference the audio sources
instead of having to search for them through code
well, you still don't have Audio assigned...
Get rid of all of that GetComponent code. Drag the audio sources in directly.
I can't have 2 AudioSources in one object.
You can stick them on child objects
you can have as many as you want
but yeah directly link is your best bet
how?
you just...add them
you can then drag the individual components into the fields
Oh I C
thx
The problem was solved 🙂
But the sound plays too late sometimes
it might be that its finishing up the file..
a work-around is to call stop on the source before u play the next clip
aSrc.Stop();
aSrc.Play();```
theres also PlayOneShot() which can allow them to overlap a bit
PlayOneShot is appropriate for sound effects, yes
some good options ^
you give it an AudioClip
use audacity and trim the end of the clip 😮
(dont)
GetComponent<Rigidbody>().velocity
this is the best suggestion but ofc can be coupled with the other suggestions
i just heard of a program called Reaper imma start to try out
if ur going to be accessing that property multiple times during ur script u may want to cache the rigidbody into a class variable that u can access instead
to avoid using GetComponent over and over
Rigidbody myRB = GetComponent
then u can just say myRB.velocity;
using GetComponent constantly is almost always wrong
lol.. im not sensing sarcasm am i?
Why can't I open doors? I followed this tutorial: https://www.youtube.com/watch?v=oCv14L3Ew4w&t=823s&ab_channel=User1Productions and this is the script:https://paste.ofcode.org/bBYr2w3L8Txn5VTgTgzHxW even in his comments people are in the same situation any one know how to fix this?
EDIT :
YES I messed up sorry. change the transition bools to open on both and it will work !!
DOWNLOAD PROJECT FILES HERE:
https://drive.google.com/drive/folders/10BvUxAOeOxZac-GfecJWSFahuMB8bOo0?usp=sharing
start debugging..
make sure that ur logic that runs the anim is being called correctly
im assuming a raycast is being used.. or a trigger
make sure those are evaluated as true first..
then make sure ur script is communicating with the script that calls the animation..
lastly make sure the bools/triggers of the animator are being flipped on
not a raycast just a cube basically look at the video of the tutorial
ohhh thx
i dont understand why u need two bools?
one for open one for closed
setbool open true would obviously mean closed is false
yea, no need for 2 bools.. just confusing
Open being false means closed
when the guy in the tutorial did it, it worked perfectly tho
yes
Lots of bad tutorials out there 🤷♂️
it isnt a very clear or smart way to do it imo
its making me go insane
does ur debugs run?
yes
on ur DoorOpens?
its probably ur transitions
try removing 1 of the bools
and only using 1 like Open
u can set open to true.. -> have ur transition go from idle to open when its true..
have it go from open back to idle when its false
then u just need to DoorOpen -> open=true
DoorClose -> open=false
Hello people
I thought lists showed in the inspector? Any reason why my available weapons list doesn't show? The weapon variable is a class btw
i have a error that i couldn't solve for a while and when i found a site talking about it, it said to remove the library file of your project, should i do it?
what is Weapon and is it serializable?
If you are looking to get help you need to send us the actual error
internal build system error. read the full binlog without getting a buildfinishedmessage, while the backend process is still running
this is the error
Weapon is a class
https://gdl.space/yiyedidohe.cs
I attached it at the bottom of my script cause I'd like to keep all combat stuff in this script
it is not serializable, you need to mark it as such or else the editor will not serialize it
Thats with one of these right? [Serializable]
yes
so what do i do?
That works!
start by making sure you are looking at the first error in the console rather than the last. and if it isn't code related, ask in a relevant channel
There are likely other errors as well.
Also read the binlog
it's the only one + what is the binlog and where do i find it?
Nope not code related
okay this is a code channel. so if you need help with a non-code related issue then ask in a more appropriate channel. id:browse
in this case, what is the appropriate channel in this server?
if only there were some way for you to view all of the channels and their descriptions so you could make that decision yourself
https://www.spawncampgames.com/paste/?serve=code_932
@hollow dawn once you debug everything you'll discover whats wrong..
because i inspected the channels and no channel i think is related to "non code errors"
then you didn't look hard enough
yes i was just saying thats how you access it
You sure about that?
then i shall look
if (Input.GetButtonDown("Interact"))
{
if (inReach && !isOpen))
{
DoorOpens();
}
else if(inReach && isOpen)
{
DoorCloses();
}
}```
also in ur code u might want to use a bool (within the script) to keep track if its open or not
That is A way to access it
Not the best one though
do u really need else if?
yes, b/c the door open and close functions set the isOpen bool to something different..
so if u dont use an else if.. the first one runs.. changes the bool.. then the 2nd one is also true all of a sudden
so it open and close all in 1 frame
pretty sure it would work just with else
Then it would run if it was not in reach
if(myBool == true)
{
myBool = false;
}
if(myBool == false)
{
myBool = true;
}```
this would be the alternative.. and this is wrong..
both if conditionals get run
the else if combats that
so only 1 set of ifs will run each keypress
ofc theres other ways to do it.. but i was working off of someone elses code.
which is odd.. since they followed a tutorial.. cuz ^ that doesn't make much of any sense to me
it would force the door closed all the time
pretty similar to this one ^
How do I edit the sprite physics? The handles that I'm seeing in the documentation aren't appearing
make sure ur collider is expanded in the inspector
how to change only the z rotation of a Object
That method won't work cause I'm using tilemaps
this is not a code question. #🖼️┃2d-tools
Oh sorry I thought I was in #💻┃unity-talk
new Vector3(transform.position.x, transform.position.y, newPos);
just modify its z pass it its own x and y back to it
but rotation is a quternion
Don't worry about the euler angles. Worry about "I want to rotate an object around a particular axis"
For that you can use Quaternion.AxisAngle for example (or was it AngleAxis?)
is better
ok ill try
when discord gonna let use have intellisense for our responses 😄
Or if the axis is one of the object's local axes, you can just use transform.localRotation or transform.Rotate
when u use localRotation, do u also switch out the axis?
say localRotation, around transform.up vs the Vector3.up
i get mixed up sometimes b/c of the way TransformDirection works
You'd hve to be specific, not sure what you mean exactly
localRotation is relative to the parent's rotation
ohh nvm
Rotate rotates around the object's own local axes
i realized what i was talkin about lmao
yea yea.. so its independent of wether its local or global
what i meant was if rotating globally it would be transform.rotation = Quaternion.AngleAxis(30, Vector3.up);
but if u wanted to rotate it locally it would be transform.localRotation = Quaternion.AngleAxis(30, Vector3.up);
my question was.. if we change it to be local.. do we still use Vector3.up.. or would it then become.. transform.localRotation = Quaternion.AngleAxis(30, transform.up);
or would we still use Vector3.up
no you don't want that
VEctor3.up would be correct
transform.up is a world space vector
okay thats what i was kinda thinking..
https://hatebin.com/etiwlcakne whats wrong with this code because when ever i put this in a game object unity says the game object cant be found
Show where you assign gameOverScreen
when ever i put this in a game object unity says the game object cant be found
Huh? Can you elaborate on that?
Is there an error message? If so - copy it here exactly
wait i misspelled i meant class of the script
SHow us what error you're seeing
Ok, now I am even more confused
Do what it says
- Make sure you have no compile errors
- Make sure the class and script name match
When you do that, it will work.
where do i check
The console window for compile errors
The console
kk
Have you gone through !learn yet?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'm hoping that is not ai code
The fully qualified class names... not sure what they indicate haha
It does look kinda like AI code
with every line commented
it is i downloaded unity 5 hours ago
wait thats a thing?
Ok, do not use ai
It describes exactly what it is right there
Tutorials for learning unity
Do the essentials pathway and then the junior programmer pathway
i have a script that is attached to a gameobject that can hold 1 of 3 different scriptable objects.
https://gdl.space/ogisaxopir.cs
i need this void to be able to tell which one it is. however, as it is now, it gives a NRE for any object that has something other than a weapon SO attached. how can i fix this? my current method is to check if a value stored in the SO is not null, but it doesnt seem to work if the SO itself is not there
correction: you need this method to tell which one it is
it's not called a "void"
its return type is void, because it returns nothing
jsut check if the SO is there first.. not if a value in the SO is there
yes, you can check if the field has anything in it
if its not there no need to check for the value
if its there.. then go deeper
Sanity check
Debug.Log(transform.position.z);
Shouldn't this print the z position to the console?
Yes
And shouldn't it be a numerical value?
those are numerical values.
It is
btw based on this log looks like two different objects are printing their positions.
unless your object is going back and forth between two similar positions rapidly
[timestamp] (log message)
(method that caused the log message)
I was reading them as time stamps... 
timestamp on the left
what is a timestamp but a numerical value 
That's a fair jab lmao
Google is on the fence
lol.. nah bro its a bank
Thank you world bank for keeping the very important data that 19.92768 is in fact a real number and not fake or imaginary
illuminati* is what i assume you mean
void Update()
{
Debug.Log(transform.position.z);
if(transform.position.z > top)
{
Destroy(gameObject);
}
else if(transform.position.z < bottom)
{
Destroy(gameObject);
}
}
For some reason this is causing my game object to be instantly destroyed when it is instantiated.
top = 40
bottom = -10
Object is being instantiated at (0, 0, 35) or (0, 0, 0)
interesting
If I comment out the else if statement, the object isn't instantly destroyed
log top and bottom as well
Debug.Log($"top: {top} bottom: {bottom} z: {transform.position.z}");```
Yeah like that
Yup, the bottom was being set in the inspector window and overriding the coded value. I changed the variables to private since they don't really need to change
This is the reason I am going through the Unity Learn course lol Trying to learn all of the little things with Unity
Real quick, in a Raycast2D, the first vector is a position(in my case relative to the gameobject the script is attached to), and the second vector is a direction that begins at the first position? or is the second vector also a position relative to the gameobject?
ex in case of first question: to have the raycast start at (0,1,0) and point in the y direction, you would put Physics2D.Raycast( [0,1,0] , [0, 1, 0] )
ex in case of second question: same thing, but youd do Physics2D.Raycast( [0,1,0] , [0, 2, 0] because if they were the same spot it would result in no direction
(pretend the [] are a variable that points to a vector like that)
little tip.. in the corner the 3 dots u can select Debug mode.. to expose private variables
just long enough to see whats happening w/o having to debug all the values
then u can switch it back to Normal
The second vector is the direction the ray flies
So it's [0,1,0] and [0,1,0]
Thank you
hey does Unity Muse AI comes with unity pro?
It works like DrawRay
i got myself so confused for some reason thinking id put two points on top of each other and the raycast was just checking a position
rather than DrawLine
yeah
I put a sprite on this square but the sprite seems much bigger, how to fix?
change the scale down to 1:1:1 to match the collider..
Just noticed that this is the wrong channel so thanks anyways for answering
ive always wondered why we couldnt adjust a sprite independently of the scale
kinda like how image components work
No idea what i just did but now when i set the sprite to the block it shows scales are already 1:1:1
But it's still massive
is it a child object of any other gameobject?
A plot is just a 2D Square Sprite in my case
#💻┃unity-talk or #🖼️┃2d-tools probably will be better suited for what ur asking about
Thanks
What's the best practice for removing bounciness when colliding? I've read increasing the mass is one trick
youre moving the player with rigidbody?
you can use a physics material to remove bounciness
but i dont think bounciness is the issue here , asyour player is moving into the collider. the fastest way to do this is to do a raycast in the direction the player is moving at to prevent them from moving into the collider for that one frame
could be able to crank up the collision detection to prevent u from entering the collider in the first place
whats happenin is the collider is pushing u back out of it
yeah exactly
Yeah, as said, this is not bounciness. Collider penetration can be helped by setting the rigidbody collision detection mode to continuous, and being sure to NOT move with the transform. Use the rigidbody itself
Okay noted! Thank you so much all