#archived-code-general
1 messages Β· Page 103 of 1
no, I didn't
prove it by clicking on the time slider field and making sure it takes you to the right place
oh, should I send the video?
that's hard to image, because the audioSource.time is -0.5 seconds I guess
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
and you're very confident that this isn't the case
I sure am
cause everything works perfect, but volume also remotes the clip a bit
I am also confident that there is indeed a mistake somewhere
because it does not work properly
what if you get rid of the onValueChanged listener from the volume slider entirely?
does it still somehow change the time?
no, I guess
you guess?
i do not understand what you have or have not done
did you remove the event listener?
hey so Im getting a object not set to an instance of an object error and the wierd part is that its checking for gameobjects with a tag and giving me an error even though there is a game object with the tag. If anyone can help that would be great
and did that change the behavior?
but no, wait, I have just played and it was also changed a bit too
then you have a typo
yes, I did
the tag it is checking for is the exact same spelling as the tag on the game object
no, that is indeed a typo
i forget if tags can have whitespace at the ends
this is the line: muzzle = GameObject.FindWithTag("LocalMuzzle").transform; and the tag is the same
well, since it didn't find an object, the tag was not the same
does this object exist in the scene?
it's not going to find a prefab
it also won't find inactive objects
the object is a child in a prefab. The player is checking for the tag and the prefab is instantiated on the player
whatever you're looking for isn't in the scene yet or isn't active whenever the code is actually running
Or the tag is wrong
without further details we can't say more than that
the tag is right because in the code i added a space to the end to see fi that was the name and then it gave me an error saying that that asnt a tag. so It should be working
Also it doesn't really sound like FindWithTag is an ideal way to handle this - why not just grab the reference when you instantiate the prefab.
how should I do that?
Instantiate returns a reference to the newly created object
would be really silly if it didn't
I need to set a variable to an empty game object that is on the muzzle of the gun. So that muzzle flash can apear. how would I do that in the way you are saying @leaden ice
public Gun myPrefab;
void SpawnGun() {
Gun instance = Instantiate(myPrefab);
Transform muzzle = instance.muzzle; // Just make the muzzle a variable on the gun script that's assigned in the inpector.
}```
put all of the references you need on a component that's on the root of the prefab
now you can grab them
yes - it's poor practice to try to reach inside other objects
ok thats pretty smart @heady iris
it adds a lot of complexity
generally speaking, you should avoid "finding" stuff
it leads to extreme agony:
finding a component in your parent is less prone to breakage, since there are fewer places to look
i do that for my UI system
all of the various bits and bobs find a UI Manager in their parent and register themselves with it
yo making a meteos clone and when i calling the meteos "packets" when i launch packets i want to make them into a "Packet group"
public class PacketColumn
{
public List<Packet> packets;
public int height;
public int xpos;
public PacketColumn(List<Packet> packets, int xpos)
{
this.packets = packets;
height = packets.Count;
this.xpos = xpos;
}
}
public class PacketGroup
{
public List<PacketColumn> columns;
public int lenth;
public PacketGroup(List<PacketColumn> columns )
{
foreach ( var column in columns )
{
foreach (var ccolum in columns.Where(c => c.xpos == column.xpos))
{
}
}
this.columns = columns;
lenth = columns.Count;
}
}```
however i will sometimes pass redundant columns (ones with the same x pos) into this group how would I go about combining them into 1 column in when defining a packet. i think I'm on the right track with the foreachloops but im not sure.
Combining them, as adding up their heights? Then yeah you're on the right track, you need to do ccolum.height += column.height in the inner for loop.
And remove all duplicate columns after that. I'd just use a second List for that
@leaden ice i am now getting the same error but on this new line: muzzle = GetComponent<GunComponents>().muzzle;
But GunComponents.muzzle is defined on all guns
GetComponent will look on the object that your component is attached to
if it's on a different object, then it won't work
onValueChanged
the script this is being called on is on the player. and the guns with the muzzle and the GunComponents script are instantiated as childs of the player gameobject
then it won't work
the player does not have a GunComponents component
call it on the gun game object
it is telling me i need an object reference to set the variables. You said that I cant do getComponent on something that doesnt have the component so how should I set the reference?
gunObject.GetComponent<GunComponents>(), for example
where gunObject is a game object that has that component on it
ok
Sorry the collums with the same Xposition are overlapping i bascially mean how would i combine them and merge the overlap
its giving me the error saying object not set to an instance of an object on this line: GetComponent<Player>().GetComponent<Weapon>().muzzle = GunMuzzle;
i didn't say to do that
i said to call GetComponent on the gun object
you need a reference to the gun object so that you can get the component from it..
ok
wdym "the same error"?
you're getting the Player component, then trying to get the Weapon component from the same game object
there's #πΌοΈβ2d-tools
2D tools would be relevant for 2D art, yes
Thanks!
otherwise, you probably just need to ask in the relevant channel for your specific problem
That's the question I'm asking. What do you mean by "merge"
is it ok practice to keep an array and a hashmap of exactly the same data, syncing them on change, and use for different purposes?
it feels very natural and very stupid at the same time
it's ok - sure. But it might not be necessary. What's the use case?
using UnityEngine;
using UnityEngine.UIElements;
/*
* This file was auto-generated by the UIToolkitAutoReferencesPostprocessor class
*/
namespace " + FolderName + @"
{
public class " + FileNameVariable + @" : MonoBehaviour
{
private VisualElement root;
" + PrivateElementReferencesVariable + @"
" + PublicElementReferencesVariable + @"
void GetVEElements()
{
root = GetComponent<UIDocument>().rootVisualElement;
}
}
}";
private const string PrivateElementReferenceTemplate = @" private " + ElementTypeVariable + @"" + PrivateElementNameVariable + @";";
private const string PublicElementReferenceTemplate =
@"" + PrivateElementNameVariable + @" =root.Q<" + ElementTypeVariable + @">(""" + ElementIDVariable + @""");";
#endregion
}
what do the @ signs do here?
thx
that's a very interesting looking file
It looks like a template file for a code generator
thats only the bottom section π
^^
grabs names and things from UI toolkit docs
ooh, I see
so I don't have to try and type everything exactly perfectly
i kind of see
however I didn't make it...trying to modify it to work exactly as I want π
FolderName is a variable above
I guess it's part of a longer string. The quote after namespace is a closing one
ah!
yes, that would do it
code generation: not even once, man
i was doing research work involving a C source generator and a source-to-source obfuscator
infinite misery all the time
like I want to do
for (int i = 0; // etc...)
for (int j = 0; // etc...)
// operate on array
and at the same time I want to have a mapping (particularly int2 to MyClass)
ofc I can just pack it into a struct like this:
public struct MyStruct
{
public int2 coords;
public MyClass myClassInstance;
}
and iterate with for loops on a struct, and still have mapping
but it feels like an unnecessary level of complexity, I'd like to go with array+hashmap way
I wanted to ask if this is a very stupid practice or it's ok to do that π
Is this for a 2D grid?
yeah
hmm... maybe you're right. I'll just iterate with foreach π€
yeah it's pointless to iterate over the empty spaces anyway
unless you need to - but in that case you can still use a nested for loop if you want
yeah you're right, I'll just go with single hashmap. thanks
By merge I mean like when I run clear check logic on the bottom 3 blocks, it will launch them, that will make a column of each of the bottom 3 blocks and the blocks above it and pass thoes columns into a new packet group, i want to know how to take thoes 3 redundant groups and combine them into one that is just the bottommost block up
Whoa
I'm having issues parsing that sentence
hello guys, i'm facing some problem here using Analytics and Dashboard. the standard events are working as gameStart, gameEnded, newPlayer and many others. But the custom event isn't working, even though I have configured and enabled it on the Dashboard.
all thats really import I guess is, it will make 3 columns (lists of blocks) each containing one of the 3 "launched"(bottom 3) blocks and all blocks above it(which for all but the 3rd from the bottom will include one or more of the other launched blocks) , how do I combine those 3 columns? into one without the overlap making multiple references to the same block?
So those 5 blocks are in a list and you want to put them into one "group", by their column index
I'd use a 2D collection, like a List<List<BlockGroup>> and dynamically add blocks to it as they come through
Hey so the muzzle flash system in the shoot function is not working and I do not know why. Can anyone help? Heres the script: https://hatebin.com/pihwyylqqh
Define "not working". What works and what doesn't.
Any and all info is necessary.
all the shooting works but the muzzle flash prefab is not being instantiated
in the shoot function on line 340
Question.. I rotate / swing a gameobject with a mouse input. I get the axis of the mouse in Update, clamp the axis between 0 and a max speed, and then apply that clamped axis as a euler to rotate the object. Everything looks and feels smooth (project runs at 300fps). Now, I need to make the input frame rate independent, so I multiply the axis with Time.deltaTime (and multiply the outcome because it's obviously a lot slower). I get the same speed of the movement, but it looks and feels way choppier then when I didnt use Time.deltaTime
no... okay when i "match", the bottom 3 blocks each block find all the blocks above it, and makes them into a list including it's self called a column, like this image, each color representing a column, how do i combine the columns into 1
I must be using it wrong somehow
Is that line of code even running? Check with Debug.Log
You don't use deltaTime for mouse input, it's already framerate-independant. Mouse delta accumulates between frames, it's a physical distance you'd say
I'm using Input.GetAxis("Mouse Y") per update though
which tells you "the mouse moved this far since last frame"
I even put the line of code as the first line of code in the function and it didnt work but the debug.log right after it worked
notice how there's already a "per frame" term in there
no need for deltaTime
Are you getting errors in the console window?
"didn't work" is very vague
if the code is running and you're not getting errors - then the Instantiate is happening
Then the object is spawning
Ahhh yeah i see now.. Thanks, that was dumb of me!
It isnt showing up in the right position then
it might be spawning somewhere you don't expect, or it might be getting destroyed right after
first place to check is the hierarchy window
ok
Is that a better way of explaining it spr2?
Here's the function with proper formatting: https://hatebin.com/wutkqzwzeq
I checked the window and the effect is spawning way outside the map
So it's working.
Modify the position and rotation to fit your needs.
Likely the data that you're wanting to use aren't good
I figured out why it isnt working. The position that is being set is the position of the muzzle in the prefab. That means wherever the muzzle is in the prefab mode is the location. How should I identify the muzzle of the gun when it has been instantiated?
By following the example I gave you like an hour or so ago
It's also kinda weird you're maintaining your own Vector3 muzzlePos variable in this script - just read the position directly from the muzzle when you need it
muzzle = loadout[currentIndex].prefab.GetComponent<GunComponents>().GunMuzzle;
You're pretty explicitly reading it from the prefab right now ποΈ
yeah and thats my issue
Im just having trouble getting the instance of the instantiated gun
it is returned by instantiate when you instantiate the gun
var instance = Instantiate(gunPrefab, ...);```
where is is returned
from the function
it is the return value of the Instantiate function
Another question relating to Input and frame rate indepenency. So, I was making the mistake in regards to Input.mouse axis etc. But, what I am doing wrong is: I am clamping the axis in Update, which is causing problems
I'm using the axis to calculate a euler rotation. what would be a good way of clamping this and making it frame rate independent?
Use a float variable to drive the current pitch of the camera and clamp that. Clamping the input value isn't going to help anything
you mean clamp the actual rotation, rather then the amount of eulers to add? But, if I do that in update, wouldnt that then Also go faster the more updates per second?
to clarify: I use the axis to calculate how many eulers to add or subtract from a certain rotation
It will move as fast as you move your mouse
it's not going to give you input values if the mouse isn't moving
Yeah i dont want that functionality (im not moving the camera but a game object)
I don't understand what you're asking
clamping the "amount of eulers to add" isn't helpful
you want to clamp the max up/down looking angle right?
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
void SwingForwards(float axis)
{
axis = 2f * axis;
axis = Mathf.Clamp(axis, 0, ballSwingMaxSpeed*Time.deltaTime);
anchorRotationEulers -= new Vector3(anchorRotationSpeed * forwardSwingSliderSpeed * axis, 0, 0);
ballAnchorRot.transform.localRotation = Quaternion.Euler(anchorRotationEulers);
ballAnchorPos.transform.position += ballAnchorPos.transform.forward * ballSwingMovementSpeed * forwardSwingSliderSpeed * axis;
} ```
calling this function per update
you're only clamping the amount to rotate by - not the actual rotation here.
the Time.deltaTime i've just added
correct
What are you trying to do
I'm trying to give the rotation a max speed
unrelated to your issue, but just FYI when posting code, don't put a space before or after the csharp otherwise it won't use it for syntax highlighting
indepently from the frame rate. So there is a max speed with which you can move the object. But slower movement is ok.
yeah I gathered that, thanks π
Then sure this will work: axis = Mathf.Clamp(axis, 0, ballSwingMaxSpeed*Time.deltaTime); except that you are then later multiplying even more things into it
There's so many different multipliers you have here - seems confusing
forwardSwingSliderSpeed
2 < a magic number
anchorRotationSpeed
yeah, it Is confusing, totally agree ha. What I'm doing is: moving a gameObejct, and then rotating a gameObject within that (kinda like a wrecking ball on a crane going forwards and backwards)
and tbh, I have no idea why I multiplied forwardSwingSliderSpeed with the position And the rotation... It's been a while since I wrote that
The 2 is basically the "Main" speed (should have been a variable). Then there is the max swing speed and max movementspeed. I was rewriting everything, so I think I'll take out the SliderSpeed ha
can someone explain what does this mean?
public class Name => name;
pretty sure this would be a compile error
unless you mean class as a placeholder
it is an example
for a type
the arrows can mean something but you cant use them like that
its like a mini function
imagine the class is an actually class with a name
if it was e.g.
public string Name => name;``` then it's just shorthand for this:
```cs
public string Name {
get {
return name;
}
}```
@leaden ice I got the output from the instantiate and got the muzzle reference from it but the muzzle flash still instantiates at a different location
it's going to instantiate wherever you're telling it to instantiate
you should avoid using keywords for placeholders
do more debugging
since that changes the meaning
the ol' reliable is Foo
or maybe just MyClass or SomeClass
basically this
@simple egret I figured out I think I should use List<>.union for it but I'm not sure how to pass a list of lists into Union
yep shorthand for a property with a getter that returns that field
as in my above example
basic lambda expressions:
public float Square(float a)
{
return a * a;
}
public Func<float, float> Square = (a) => a * a;
either way you can do float num = Square(2);
But, axis = Mathf.Clamp(axis, 0, ballSwingMaxSpeed*Time.deltaTime ) still doesnt seem to give me the desired behaviour unfortunately. The higher the FPS the faster the movement..
ok then what's the point of it?
wdym?
It defines a property that outside classes can call to read that data
sortedList = itemsList.OrderByDescending(o => o.item.rarity).ThenByDescending(o => o.item.level).ThenBy(o => o.item.itemType).ThenBy(o => o.item.name).ToList();
soo
you dont have to write
public InvItemData ItemData ()
{
return itemData;
}
or use brackets every time
this should have all legendary items at the top...then it should sort and so the highest level legendary item is at the top right?
why does an epic item(leveled above everything else) take precidence here and go to the very top of the sort?
what you're saying is that when you do that other classes can only get not set?
i presume your rarities are represented as an enum
read-only
yessir
yes
that's one side effect
show the enum
public enum MyItemRarity
{
Common = 1,
Rare = 2,
Epic = 3,
Legendary = 4,
Mythic = 5
}```
similar to { get ; private set }
you sure that level 6 thing has the right rarity? Maybe it's colored wrong
also don't you want descending rarity?
if you want mythic first?
thats what it is rn π
oh nvm you have that
then this thing => pretty much means return
it's used to write a method that's just an expression
everything sorts correctly until I level up items
which implicitly returns the expression, yeah
in that case yes
nevermind Im stupid
was sorted by slot and not rarity....
sortedList = itemsList.OrderBy(o => o.item.itemType).ThenByDescending(o => o.item.level).ThenByDescending(o => o.item.rarity).ThenBy(o => o.item.name).ToList();
that was the actual code
splat
quick check, if I have GameObject GO = null will GO.transform be null or throw an error?
it will throw an exception.
thx
dereferencing a null ref will throw an exception
null.anything will give you an error
But you can use a null conditional operator if you don't want to manually check if GO is null first
GO?.transform
If GO is null, the following property accessor won't be evaluated, and the result of the entire expression will be null
eeek
in general yes
but in Unity - with UnityEngine.Objects, no
this won't work properly with Unity's overridden == operator
i.e. if the object is destroyed, it will still try to access the transform
and you'll get a MissingReferenceException
That is really good to know
so in general - try to avoid the ? family of operators with UnityEngine.Object references
you can make an extension method to make ? work with Unity objects
I know just enough to confidently say something stupid and hope you all catch my mistakes π
welcome to the club
Would you mind providing an example, out of curiosity?
Ah I see - thank you! π
Can someone write me code for an entire open world game pls@I will pay $5
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
can you take your trolling bullshit elsewhere. it's not appreciated here and there's no off topic allowed here
Why r u so angry lmao
who said hes angry, off topic stuff just isnt allowed
using the new unity input system is it possible when disabling the gameobject to not disconnect the controller from it?
is there any standard approach to how movement/leg collisions with active ragdolls should be done? Just curious if there is another method that i havent tried
I have a character setup with configurable joints, and a script for each body part to copy a walking animation. This works fine when the character is in the air but im running into issues where the legs just wont stop colliding with the floor which stops the hip movement [see image 1]
I tried setting the feet to be frictionless, but this doesnt fix the issue on upward slope. Also the player slides around, which is annoying to deal with.
I tried adding a constant force component to the hips and it works nice on the ground. On slopes however i can see the feet moving but they keep colliding and sometimes just drag on the floor
also tried animation rigging but it doesnt seem to be what i want because it kinda takes away from the active ragdoll movement (and im horrible with using it on a moving ragdoll)
IEnumerator TapToClose()
{
yield return new WaitForSeconds(1.5f);
var tapToClose = root.Q<VisualElement>("TapToClose");
tapToClose.style.display = DisplayStyle.Flex;
}
StopCoroutine(TapToClose());
this is how I would stop the coroutine so it doesn't execute if its been waiting for...say 1s out of the 1.5s
(cause it isn't working)
If you're wanting to use it with an IEnumerator, then you need to pass it the same IEnumerator as you passed into StartCoroutine(). There, you're creating a new instance.
The docs have an example https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
didn't know that thanks!
Funny thing that is happening on my code
I am calling a function that clears my inventory and then another function that adds a item to the first open slot.
If i call the function one time, it clears and then it adds the item to first slot. But if i call the function again, it clears the inventory but it then adds the item to the second slot instead of the first
I dont know why this is happening
for (int i = 0; i < inventorySlots.Length; i++){
InventorySlot slot = inventorySlots[i];
if(slot.transform.childCount == 1){
Destroy(slot.transform.GetChild(0).gameObject);
}
}
}```
``` public void AddItem(Item item ){
for (int i = 0; i < inventorySlots.Length; i++){
InventorySlot slot = inventorySlots[i];
if(slot.transform.childCount == 0){
SpawnItemn(item,slot);
return;
}
}
}```
so you do clear, add, clear, add?
yes
On the second add, the item spawns on the second slot
No, goes to the first
I placed a log on the add item
and its doing 2 times when the time he places it on the second slot
Its really strange
oh!
it's because the object isn't destroyed until the end of the frame
unparent the objects' transforms before you destroy them
i've had this problem many times
e.g. while (transform.childCount > 0) { Destroy(transform.GetChild(0).gameObject)); }
this spins forever
It worked!! Thanks!
Does anyone know what the error 'Assets\Character Controller\Scripts\Components\PlayerStats.cs(6,13): error CS1012: Too many characters in character literal' means? The code its talking about is [Header('Stats')]
i.e. a literal that represents only one character
Thanks.
are scriptable objects mainly meant to be interacted with through the editor?
in terms of defining their values
Is there a reason why private void OnCollisionEnter(Collision collision) { if (collision.gameObject.Tag == "Player") { tankHealth.TakeDamage(damage); } }
Keeps getting me a Namespace name can't be found CS0246 error when I try calling the health script over
I just thought about this, but why shouldnt camera input be frame independent
Isnt it better if sensitivity is the same for everyone
Share the whole error.
Kinda yes.
What do you mean by "camera input"?
Sorry I meant mouse input for camera
Assets\Scripts\EnemyDamage.cs(7,12): error CS0246: The type or namespace name 'TankHealth' could not be found (are you missing a using directive or an assembly reference?)
Mouse input for camera..?π€
Like first person camera controller
Sounds like you didn't define your tankHealth variable.
and for that line I have
public TankHealth tankHealth;
Do you have TankHealth class in your project?
Yes in the script I'm trying to call as a public class
If you refer to mouse position delta, then it doesn't have anything to do specifically with camera. It's simply so that you get consistent input over several frames.
Share the TankHealth script.
yeah, but I hear people say all the time that you shouldnt deltatime-mouse input
You shouldn't. Because it's already in the context of the difference between frames.
You usually need to multiply a constant value by delta time, because you want the portion of that value based on the time between frames.
Mouse input is already a portion of the movement that the mouse moved between the frames.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
can someone help me my games not downloading the packages i need
I don't see a problem here. Share the script where the error appears.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I can only assume that they're in different assemblies.π€
line 24 should be tankHealth.TakeDamage(damage); though
@cosmic rain After everything it's now saying this it seems like
Assets\Scripts\EnemyDamage.cs(24,24): error CS0122: 'TankHealth.TakeDamage(float)' is inaccessible due to its protection level
Because TakeDamage is private. You should be able to solve that if you post in this channel.
I appreciate the help, thanks! @cosmic rain
do the pathways on the learn site, they go through everything you need to get started
start with unity essentials
how do I make it so that an object doesnt rotate around the origin
i want it to rotate around the center of itself
if that makes sense
heres the code im using
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
playerBody.Rotate(Vector3.up * mouseX);
}
}
what do u define as the center of itself, if not the origin?
also don't multiply mouse input by delta time, mouse input is already frame rate independent and anyone teaching otherwise is wrong. when you remove that make sure to lower your mouse sensitivity variable both in the script and the inspector
like if your turning your head not moving in a circle around a point
basically just an FPS
ok I did that thanks
sounds like the object isn't properly centered on its parent object and you are rotating the parent
its in the center of it though
you would turn your head by moving your head around the origin..
what is the position it shows in the inspector
can u show a screenshot, something is likely not setup correctly
its in the middle but not exactly because I like this perspective more
yeah not centered
how do I center it
the child object should be at 0 on both the x and z axes so that when you rotate around Y it rotates in place
im very confused by this image, how is that box at -15x and 2.11z but the camera is right beside it at 17x. Also what is parented on what
Ohhh I get it now
The empty player object was somewhere else but I thought it was aligned with everything else
(I thought it had the collider on it but it did not)
so it was rotating around that
not the origin
its parented on an empty but I didnt realize that it wasnt anywhere close to the camera
So, now that my script is working, how do I add vertical rotation to this camera script? I tried a bunch of things but everything either behaved in an unpleasant way or flipped the rotations or messed up the Z and I have no clue what was happening.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 3f;
public Transform playerBody;
Vector3 amongus = new Vector3(1,0,0);
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
playerBody.Rotate(Vector3.up * mouseX * mouseSensitivity);
}
}
have you tried cinemachine? seems like you're trying to code something that exists
myPlayer.eulerAngles = new Vector3(myMouseX, 0, 0);```
It's going to look something like this
avoid rotating quaternions for something like this
It's going to look very similar for vertical camera movement. I probably have the axes wrong as well.
i got it
Just added the Y and it works now just inverted
i guess the eulerAngles thing did the trick thanks
@tender fogYour mouseX and mouseY variables will also need to be global
not local
since the values need to be saved between frames
how do I do that
yeah I did that
great
it gave an error since I refferred to mouseX in the definition of mouseX
thanks man
I am using Native Gallery to get audio and play it. Can anyone tell me why is it too loud? like even If I put audio volume to 0.0001 it still is too loud. https://gdl.space/imugasocoq.cs
did u uncomment the parts about volume by chance, because its commented out in that script
I think the audio is too low quality. how do I fix this?
Getting better sound clips
original audio is good quality. but when I play it it sounds too low quality.
go to the audio file in unity
https://gdl.space/afahematuc.cs WavUtility.cs
are you playing it with a custom script?
This is some pretty advanced stuff
It's likely a low sample rate or something
since you're designating that
I am using Native Gallery: https://assetstore.unity.com/packages/tools/integration/native-gallery-for-android-ios-112630
log the sample rate
and probably number of channels
those are going to be the main factors in dictating quality, I believe.
If they're different from the original audio source, then that's your problem
How would I get an object that is being clicked on by my cursor? I'm making an rts style game, and I have my camera and cursor working correctly as far as movement goes, but am having some problems with selecting an object. This is the code I have for converting the mouse position from screen space to world space, but I'm not 100% sure it's correct. I've tried using an OverlapSphere or a raycast, but couldn't get either working. I think raycast would be the way to go, just couldn't seem to get it setup correctly I guess.
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
This Unity tutorial will teach you how to select objects using raycasts.
#UnityTutorial #Raycast #GameDevelopment
π¦ Download the project at https://www.patreon.com/posts/25656838
This tutorial was created in part with Jason Storey (apieceoffruit). Learn more about Jason b...
Disclaimer: I haven't actually watched this vid. I just know it exists
wow wtf how did this not show up in the last hour of me searching. lol. Thanks, I'll check it out!
Ah found it. I was using ViewportPointToRay instead of ScreenPointToRay. Using the right function fixed it!
Hello everyone, i need some help with.. uh.. i donβt even know how that problem is called
i need to connect all nodes (the doorways) on a grid with hallways in my map generation algorithm.
The result of generator should look something like that on a picture.
I donβt know what approach to use here (pathfinding? cellular automata? graph?) and i donβt even know how that problem is called so i cant find anything on internet
the corridors must be able to connect with each other to minimise overall length of network, not just connect two points in space
Either lookup some sort of procedural room/hall generation, design predefined area templates or a combination of both.
Your illustration shows tendency to pathfinding
what do you mean by predefined area templates exactly?
Usually you'd have a collection of rooms or areas and simply randomize the selection of which is to be placed rather than procedurally creating entire mazes/dungeons.
well it looks like it, but most pathfinding algorithms tend to just connect two dots in space
There is multi-agent pathfinding where multiple pathes cannot intercept, pretty much the opposite of what i want
well, i have a couple of room prefabs, but i want them to be connected with small corridors
i think this is some kind of network optimisation problem?
Doesn't sound related to networking.
Sounds like you simply need to implement some sort of procedural generation of connecting rooms using rules and whatnot.
I have a game where the player should be at the bottom of the camera and followed by the camera. However, whenever I add an offset to the camera's position in update, the camera y position just continuously decreases. Code:
Vector3 targetPosition = new Vector3(player.transform.position.x, player.transform.position.y-(screenHeight/2), -1); transform.position = Vector3.SmoothDamp(transform.position,targetPostion,ref velocity, smoothTime);
What do you mean by y position just decreases?
It goes negative infinitely?
it goes negative until it reaches a floor like -1000 smth
Unless the camera is the player, it should just be the players position minus some offset.
Are you reassigning the offset anywhere?
nope
Are your references set up correctly? The only time I had a camera fly off to infinity was when it was trying to point at itself
Make certain the player isn't the camera
Relative to variable references
yea i printed out the values and they all are correct, only when I add the offset does the camera position go crazy
right
If the player was the camera, what you're describing would happen.
no the player values are correctly used
and the script is attached to the camera
when i don't add the offset, the camera tracks the player at the center of the screen
You'll need to show us some logs, the hierarchy or the inspector
The code is perfectly fine otherwise
It's most definitely a setup issue
um, you mean like create a room, connect it to the other rooms, and then create another room?
β¦i really donβt get what you mean by βconnecting rooms using rulesβ sorry
Well, you've already got the rooms.. you're simply wanting to procedurally connect them. There ought to be lots of tutorials on procedural room generation. You'd just need to find one that does the rooms first, then connects the rooms. Where you'd only need the second half of the algorithm.
The rules I'm referring to are if halls are allowed to overlap with other halls, rooms or whatnot.
So either your offset is growing negatively, your player position is decreasing in the y axis or something else is occurring.
Assuming you aren't using some sort of local velocity variable - it needs to persist per iteration.
Showing more code may be necessary at this point
i removed everything in my code except the print statements and the code i listed above
the "height" variable is just a number
I'm sure you've got more than that
Log the offset
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class Movement: MonoBehaviour
{
private Vector3 velocity;
private float width;
private float height;
private gameObject player;
void Awake()
{
width = (float)Screen.width / 2.0f;
height = (float)Screen.height / 2.0f;
}
void Start(){
velocity = Vector3.up*Time.deltaTime*.25f;
}
void Update()
{
Debug.Log("CAMERA POSITION:" + transform.position+"Offset"+height);
Vector3 targetPosition = new Vector3(player.transform.position.x,player.transform.position.y-height,-1);
transform.position = Vector3.SmoothDamp(transform.position,targetPosition, ref velocity, smoothTime);
}
}
`
How to post !code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
velocity should just be zero vector - you'll not be able to assign it the value of a float (Start)
The above should not compile
forgot to add its Vector3.up*Time.deltaTime*.25f
You shouldn't need to set the velocity, smooth damp would manage it.
oh
Where do you define player? it's private and not accessible by the inspector.
how list resize
is it detect when the count>=capacity then double the capacity and new T[] then copy all elements from old array to new allocated array?
i read the code from here:
https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,9808f1f5ef16c436
Don't know the specifics but that's usually the case
RaycastHit hit;
if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
{
if (hit.transform.TryGetComponent(out CityPointObject city))
{
citySelected = true;
cityNameText.text = city.cityData.cityName;
cityDescText.text = city.cityData.cityDescription;
cityPopulationText.text = cityPopulationText + city.cityData.cityPopulation.ToString();
}
else citySelected = false;
}
Why cant it get the city object? everything seems right
You can set a predefined capacity if needs be, for less reallocation
i was messing around with the code i forgot i needed to change it to public
What's line 34
cityNameText.text = city.cityData.cityName;
It's an nre, line 34 has an nre.
cityNameText is null or city.cityData is null
i think the problem is that the offset height value is 1170.
Yeah im just unsure why it isnt referencing
Im assuming CityData, though its referenced
Have you even determined which thing is null yet?
I think you need to log those values and see if they're changing
Don't assume anything
Ill debug more rn
i did and its at a constant 1170
and the y position of the camera ends up being-1171
im testing the game on mobile so the screen height values might be off
So if height is that fixed value, then is the player position changing? (doesn't matter if he doesn't look like he's moving with the camera in game)
Is the position changing? Should it be a local position?
if(city != null || city.cityData != null)
{
print("not null");
}
This prints
the position isn't changing, there are no forces on the player, the player is kinematic
so city name text was null
city != null || city.cityData != null || city.cityData.cityName != null this also prints
I only say so because if the camera was referenced, the position would never be matched and this you'd go to negative infinity
Use and not or
Any of them being individually true would print with or
None of them had better be null rather than "well.. if one isn't null, let's print!"
Could have multiple objects, etc.
i think it might be a problem with scaling a phone pixel height to unity's coordinate system. thanks for the help, i got a few other bugs fixed
Please just learn to use the debugger instead of wasting time with a bunch of logs
if(city != null)
{
print("not null 1");
}
if (city.cityData != null)
{
print("not null 2");
}
if (city.cityData.cityName != null)
{
print("not null 3");
}
all prints
ill try rn
It never prints if it is null
so if there's multiple objects, one of them null, you get no info
Also, cityNameText was never checked
oh no
Basically the program had already determined that one of the three possible references are null. It's simply up to you to find which one.
Im too ashamed to even say what the issue was
We don't care about the city name btw. Only references who are calling members can throw
But Yeah I fixed it thanks
You forgot to assign it in the inspector π
hey peeps! im looking for a better way to do this im doing:
So, I have a list of entities for my game stored in a list. These are bussines entities (most likely will end up in a DB after prototyping). These entities have an ID.
To make it easier to play with these in the code, the ID is of the type of an ENUM, so I always know what im getting (ie: enum has UNIT_A, UNIT_B, so when getting something by ID "1" i just get by enum.UNIT_A)
This is really comfortable to manage stuff in the code - but it has a problem; every time that i add something to that list, i have to add a new entry on the enum. And its getting really uncomfortable.
Is there any way to do this without the enum?
Or maybe a way to "Create the enum" automatically when I change stuff on that list/db?
I think if each entity will be of a unique type you will need to keep a variable for the Enum.
You could just have a list of strings instead but you will need to know how to identify them.
Hard coded strings
What are the business entities do they all different from each other
i wanted to avoid the idea of doing a GetEntity(value) with a value that I can get wrong. Thats the beauty of the enum
In OnValidate you can check if a new element was added. If so, you could generate the script file from scratch, automatically increasing the enum size.
this sounds really interesting - ill take a look
thanks a bunch!
Avoiding enums works well if you want the logic to be less code dependent. It's especially desired when you have to create tools for game designers.
mmmh then how do you solve the "getting the name of that entity right" problem? just using the value as suggested above?
well maybe you can do that and just create methods for more important entities
liek "GetEntityTownHall" and insider its just "return GetEntity("town_hall_id")
Depending on the situation I would just stick to enums, or create a ScriptableObject/Prefab for each entity so I could use those as a reference everywhere. The second approach ensures that the code won't contain any enums, so all the restrictions have to be configured through the inspector, therefore all the game rules would be more modular and could be created by game designers. But in the end, enums seem to be much easier to use if only the programmer is responsible for the game logic.
The PlayBackgroundMusic() method is called several times in Update(), because audioSource.clip cannot be set instantly. How do I avoid it?
Should I use some kind of Coroutines with WaitUntil or just bool? Do not know how though.
private void Update()
{
if (audioSource.isPlaying)
{
if (!changingTime) timeSlider.rawValue = (int)audioSource.time;
ChangeTimeInputText();
}
else
{
PlayBackgroundMusic(); // this method :[
ChangeTimeSlider();
}
}
I found using Scriptable Objects is a bit uncomfortable because you have to iterate through several files on the unity editor instead of the IDE to make changes; instead of a database for instance.
Unless there is something I dont know here?
It's just like you described: it moves the workflow to the Unity Editor.
been trying to figure this out for hours
am getting sick of it
this is a school assignment due in a couple days
help is needed lmao
all i want is for the enemy to chase the player π
You're pretty much trying to put a cube-shaped thing, into a triangle-shaped hole
.rotation is a Quaternion, a type that represents a rotation on 3 axes. But you try to put a single number into it
You cannot do that
its supposed to make the enemy look towards the player
and then i wanted to make it follow the player
and attack it
Okay, so select the enemy in the scene and look at the arrows that appear. Is the enemy's forward direction towards the blue arrow?
i believe so...
but their is a red arrow going another way
or to the right of it
Yeah that's normal, as long as the blue arrow points "forwards" it's set up correctly
And that the green arrow points up also
yep
So you construct a direction vector there on the first line, so you can use the handy Quaternion.LookRotation(direction) function, so Unity constructs a rotation Quaternion for you
Yes the first line
You can remove the second one entirely, you won't be needing it anymore
done
Then use Quaternion.LookRotation(direction), put the result of that immediately into rb.rotation
And that's pretty much it, 2 lines
Where did rb.rotation go?
replaced it with what Quaternion.LookRotation(direction)
When I say
Put the result of
XintoY
I mean,Y = X, in code
this
Y = X assigns the value of X into Y
there is no x or y though so im very confused
It's example names
Apply it to the sentence here
so how do i get a result out of Quaternion.LookRotation(direction)
like do i just put that in
Try it
Aight
Vector3 direction = player.position - transform.position;
rb.rotation = Quaternion.LookRotation(direction);
Do yourself a favor and !learn how to work with Unity scripting
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
alright will do thank you for the help
hello, I have a problem, when doing
button.transform.SetParent(buttonParent);
it does nothing, same for doing it when instantiating and/or doing
button.transform.parent = buttonParent;
For UI objects it's better to set the parent as you're instantiating them. Instantiate() has a few overloads where you can pass a parent Transform as the very last argument
Button button = Instantiate(buttonPrefab, buttonParent);
I'm doing this but it just instantiate's it on scene and not parent
Then debug required, is buttonParent assigned to the value you're expecting
yes
Prove it
In Instantiate maybe, but for the other versions no
what else could be be causing this?
Nothing, the code is correct
something in prefab/hierarchy?
Maybe it's not executing on the object you think it is? Use something like Debug.Log(buttonParent, gameObject) and once you get the log pause the game, and select that log, it'll highlight the object that sent it in the Hierarchy
YES
thank you
I was accidentally executing the code on manager instead of the correct object
and wasn't actually passing the parent object
so wouldn't this be a bug? when a null parameter is passed for transform but no error is thrown?
For the parent no, passing null unparents the object
Library\PackageCache\com.unity.burst@1.8.2\Editor\BurstAotCompiler.cs(981,27): error CS0234: The type or namespace name 'AndroidExternalToolsSettings' does not exist in the namespace 'UnityEditor.Android' (are you missing an assembly reference?) any fix for this werid error?
no way it fixed its self by just waiting
Hello,
I hope this is the correct channel to post this question in. I have installed Unity as a flatpak on Manjaro, and I am trying to setup autocompletion with omnisharp in Neovim. The LSP setup part is pretty easy, but the problem is that using the generated C# scripts, I am having errors.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
On line 3, the program is not finding UnityEngine. What I have found after googling, is that I should have a Library/UnityAssemblies folder, which does not exist. I have tried the many ways to create it, for example by closing Unity, deleting the Library folder, then reopening Unity, but it still doesn't work.
The same error is happening in the 5th line, with MonoBehavior
Thanks in advance for any help
Hello, why it says there is an error even though there isnt any?
You're not supposed to build a Unity project. Unity takes care of that for you.
Just make sure you saved, then go back to Unity and it'll pick up your changes and compile them for you
But I use this
Unity can run normally but when I want to attach VS for debugging it isnt possible
is VS your default editor too?
Yup
switch
VS will show the build errors in the output log
Yeah I know but there isnt any
I'd try closing both Unity and VS, then open Unity and regenerate project files
Yeah im going to try it
I closed everything rn
nuke .vs folder
Sorry to "step" into your conversation but can somebody please help me on this?
Yeah it helped! Thank you! But anyways my script doesnt work :c
It doesnt get triggered
hey
i'm trying to make a madness combat game but i can't quite figure out how to import the flash sprites
not able to help with the issue, but for what it's worth it's quite a niche question and this is a channel for general scripting - you might have better luck finding someone familiar in a channel like #π»βunity-talk
Okay thanks.
can u guys help
please, explain the issue you are facing in a more appropriate way so that someone can understand
ok
how can i do that
you mean import in unity?
Can anyone help me please? Why it is not triggered on click?
Import in Unity? What's the problem then? Just drag
do you have physics raycaster?
how can i detect if 2 ui / images collide with each other?
UI Image do can have Collider Component
i dont know efficient way but the one i used is to extract their bounds and test for overlap
which collider should i add box collider?
or box collider 2d
IDK what else can be bad :C
yes, Box Collider 2D
ok i added them this is my code btw
void OnCollisionEnter2D(Collision2D collisionInfo) {
if (collisionInfo.transform.tag == "Shrine") {
Debug.Log("succesfully found shrine");
}
}
why is this not working?
i have this code in my cursor image
is this correct?
what do you mean?
this code
you should have pinned, when sending the code
pinned? wym
that's good, but you'd better use collisionInfo.transform.CompareTag("Shrine")
the problem is that it's .fla
pinned is like: "@gray mural, hello, yeah, is my code correct, @gray mural?" I guess ??
oh alr but my code doesnt work
it does print out
it does? then it works
and?
just drag
I have downloaded what you have sent and dragged it, everything works
unity imports .fla?
for me it doesn't
oh, I see
By... reading what that page says. Instructions are pretty explicit
i have not checked it, yeah, it does not
nah, that's not the point
just in the assets
i am trying to figure out a way to use the sprite sheet inside unity
no, there is no .png variant of it
find fla to png converter
i mean it doesnt sry spelling error
maybe you can convert to some vector format
i'll try it
Well how could I have guessed the sprite asset was the issue lol, you posted no context at all!
It's probably not a code issue either way
unity has vector sprite package but i dont know if it supports fla
@narrow lily You should go to Adobe Flash (cause .fla) and export the file with another format like swf, .fxg, .png, .jpeg
yeah, there is no collision then
but there is i m going over the other image
i m making a map
let's see possible errors
ahh
okay
i have a cursor that moves with WASD
so i do need flash
and i m going over another image
but no printing
and it has a boxColider2D and the correct tag
-
There is no collision (for example the Z posiion is not the same)
-
One or both images do not have
BoxColliders2D -
There is no image with
Rigidbody -
BoxColliders are triggers (make them collisions or use
OnTriggerEnter2Dinstead)
mhm okay lemme try
don't forget to pin me afterall
@gray mural i do not know if i did anything wrong but i tried everything but it doesnt seem to see any collsiion
i tried adding rigitbodys too
and i checked the Z position too
both the same
you should have 1 rigidbody
@swift falcon
paste this code:
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
Debug.Log("There was indeed a collision");
if (collisionInfo.transform.tag == "Shrine")
{
Debug.Log("succesfully found shrine");
}
}
ok
Hello everyone !
I am trying to create a spell for my 2D top-down game, where the player can create an energy beam that continuously damage enemies (think Disintegrate from Diablo 3). The beam is "single target" : it originates from the player, and ends where it hits an enemy, dealing damage to the enemy.
I was thinking of implementing it using 3 prefabs : a "head", a "body" and a "foot", so that I have the foot that stays near the player's position, the Head that stays near the enemy position, and the body that extends between the head and foot, using continuously-tiled sprites to repeat it and get a beam that adapts itself to its length.
I have a problem, though : I don't know how to handle it so that is a second enemy moves and hit the body part of the beam, the whole beam becomes shorter, and the head's position is now at the place where the second enemy is.
Do you guys have any advice on that ?
nothing coming out in the output
my brain has stopped working idk wh yits not working
there is no collision at all then
send the video and also you'd better create a new thread
that collider is marked as a trigger
I have said you already
yes
it will not receive collision messages.
wai wha
still doesnt work even if i turn it off
here:
-
There is no collision (for example the Z posiion is not the same)
-
One or both images do not have BoxColliders2D
-
There is no image with Rigidbody
4. BoxColliders are triggers (make them collisions or use OnTriggerEnter2D instead)
another is also trigger then ??
somehow ??
idk what i did but i repeated the 4th step u gave me
glad to hear
what π€―
Basically, as I understand it, they want a Line Renderer
And a raycast to detect hits
Looking at https://docs.unity3d.com/ScriptReference/Physics.Raycast.html I think it only tells true/false whether the raycast hits something ?
Is there something similar which tells me what is the first collider hit ?
there's a constructor with an out variable
RaycastHit will contain information on what you hit
oh, ok
I did not really understand the example in the doc, but the one from the 2D version is much clearer
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
I have a grenade that casts an overlap sphere. I want to limit what can be grabbed by the sphere for performance concerns. Though the root of my enemies don't have a collider. only limbs (the component I want to grab is on the root).
I've made a layer called IDamageable on the root of my enemies. is it "normal" or "standard" to have a small collider inside the mesh of the root so that nothing can physically hit it, only the overlapsphere can grab it. to deal damage to the enemies?
I've done similar things before, yeah.
I don't think you can create a "point" collider
so a trigger collider that's roughly proportional in size to the enemy would be reasonable
Does somebody know my even with playBackgroundMusicCoroutine the "Changed BG Music" is printed 1-3 times when audioSource ends?
private Coroutine playBackgroundMusicCoroutine;
private void Update()
{
// ...
if (audioSource.isPlaying)
{
if (!changingTime) timeSlider.rawValue = (int)audioSource.time;
ChangeTimeInputText();
}
else
{
if (playBackgroundMusicCoroutine == null)
{
print("Changed BG Music");
playBackgroundMusicCoroutine = StartCoroutine(PlayBackgroundMusic());
ChangeTimeSlider();
}
}
}
private IEnumerator PlayBackgroundMusic()
{
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
audioSource.Play();
yield return new WaitUntil(() => audioSource.isPlaying);
playBackgroundMusicCoroutine = null;
}
i wonder if it's taking a few frames to load the audio
yes, it does
does the behavior change after the music is loaded once?
that's why I have done Coroutine to make it load just once
what do you mean?
ah, but it shouldn't be running the coroutine twice, 'cos it sets playBackgroundMusicCoroutine
does it only happen the first time the music is played?
every time I remote the music, the void is called approximately 1-3 times
Whats the purpose of that WaitUntil?
i wait wanna wait until the audioSource is being played and then set backgroundMusicCoroutine to null
so that that this part of code won't be called a few times:
print("Changed BG Music");
playBackgroundMusicCoroutine = StartCoroutine(PlayBackgroundMusic());
ChangeTimeSlider();
and it should work I guess ??
it doesn't though
I don't really get it, why would you wait until it's playing
you just called Play, surely it's playing
it takes a few frames to be played
but why are you waiting for that, and then immediately starting a new coroutine to play something else
oh! I seee
"play some music"
"oh, I see you have started playing that music I asked for"
"play some music"
yeah
stop
no
not I seee
the coroutine waits until isPlaying is true, then it clears the playBackgroundMusicCoroutine variable
if we work under the assumption that isPlaying is only true once the audio clip is actually loaded and playing, then this would be reasonable
how can i find an object in the game with a name? so i have a name stored in a variable and i wanna find an object with that name in the game how do i do that?
why would this be reasonable
because you don't want to tell it to start playing a clip every frame until isPlaying becomes true
but, again, this is assuming that isPlaying doesn't immediately become true..
why would you want to play something when isPlaying comes true?
surely you would want to play something when it ends
if (is playing music)
{
do smth
}
else
{
if (bg coroutine is not being executed)
{
then we change it's clip
}
}
if isPlaying is true, the code doesn't do anything
private IEnumerator PlayBackgroundMusic()
{
set clip
wait until the clip is set
}
if isPlaying is false, it tries to change tracks, but only if it isn't already trying to do that
dont know why i asked it to be honest it got in my head 10 seconds after
yes, indeed
Ah I see, this is truly a bizarre way of doing this though, and I suspect that the bizarre way it's set up is the issue
have you checked that isPlaying doesn't immediately become true?
although, even if it did immediately become true, I wouldn't expect this code to malfunction
can you find the better way then? π
do you have a problem if you don't do the coroutine business?
if you just pick a random clip and start playing it in the else block?
yes, of course
does it try to change the clip many times?
I have done the coroutine to fix the issue
yes
1 to 3 times
while it's loading
so it is changed within 3 frames
yes, also
Why don't you make your own booleans for this then?
it's weird to use the coroutine as a boolean to see whether the audio has begun playing, when you could just set a boolean when you play music and, not use a coroutine
the PlayBackgroundMusic() IEnumerator was just normal void before
playBackgroundMusicCoroutine is acting as as mutex
indicating that the coroutine is currently running, and that you should not try to start another instance of it
yes, I know, I have asked here, cause I don't how to do it. Maybe you can give a bit more explanations?
yes, but should work this way
and I do not see any reason for it not to work
it does seem correct to me
yes, I have tried, but I didn't succeed
the only thing I can think of is
does isPlaying stay true when you ask to play the clip
but then become false as it starts loading the clip?
So. Actually. It does work. It does changed the clip and everything works in this way. But it changed the clip few times.
"correct" as in "only fires once"
that would make this behavior possible
no, works everytime, but few times
Update -> start coroutine -> play audio clip -> yield -> WaitUntil finishes because isPlaying is still true -> coroutine finishes -> isPlaying becomes false as the new clip loads
oh, wait, I have an idea according to this
that's the hypothesis, at least
it may be
maybe you should Stop() the audio source
see if that changes the behavior
i've never really relied on isPlaying for anything, so i wouldn't have seen this before
but i can believe it
so I have done this:
yield return new WaitUntil(() => audioSource.time >= 0f);
playBackgroundMusicCoroutine = null;
but there is still the same issue
and that's really strange
have you tried putting audioSource.Stop() before you call audioSource.Play()
yeah, wait for a while
it's try it rn
also, i'm pretty sure this would always be true...
yield return new WaitUntil(() => Mathf.Approximately(audioSource.time, 0f));
playBackgroundMusicCoroutine = null;
this also does not work
yes, but have you tried the thing I suggested...?
yes, I am trying it now
stop the audio source, maybe even log isPlaying before and after to make sure that does something
you should really be logging that already, so that we aren't just guessing at how it behaves
like this?
private IEnumerator PlayBackgroundMusic()
{
audioSource.Stop();
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
audioSource.Play();
yield return new WaitUntil(() => audioSource.isPlaying);
playBackgroundMusicCoroutine = null;
}
the time stays the same in the next clip and throws error if the previous clip was longer
perhaps until it starts playing again
since Stop() makes it start playing from the beginning when you eventually call Play()
so, has this changed anything?
no, it's the same
private IEnumerator PlayBackgroundMusic()
{
audioSource.Stop();
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
audioSource.Play();
yield return new WaitUntil(() => audioSource.isPlaying);
playBackgroundMusicCoroutine = null;
}
Well, I used the original code and it only prints once every time it plays
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
slap some debug statements in there to find out what order things are happening in, and what the values are at each point
that will be a lot easier than spitballing
Why do you call PlayBackgroundMusic in Start without assigning the coroutine
https://forum.unity.com/threads/unity-crashes-badly-during-run-time.1434310/
heya...so i have this issue which is mentioned clearly on the forum, but here's the briefing.
during run time, at a certain time (mentioned on the post), my unity engine stops responding...and ive to force quit it in task manager. i tried to export the game in hope that it was just an engine fault...but it still happenes... i think it is due to the code sucks... can anyone pls help me out? this was for a game jam... thx.
ps: i posted this thing in #archived-code-advanced 'accidently', and they said to debug it (like adding a breakpoint, still nope, it crashes badly)
why should I assign it in Start() too?
because the whole point is that you use that variable as a mutex
you must never have more than one instance of that coroutine at once, right?
oh, maybe
have you actually verified that isPlaying doesn't become true (and stay true) after calling Play?
while(kidBall.bodyCount >= 3)
{
BackToNormal();
// confused= false;
// isMoving = true;
// isShootable = false;
}```
This is an infinite loop, kidBall.bodyCount is not changing inside the loop so it'll never exit
if not, all of this is pointless
I have corrected, the issue is still the same
you cannot fix a problem that you do not understand
oh
one sec
Well, the code definitely works fine for me. I'm not using your whole thing though as I cbf setting all this up
I can only imagine there's a few instances of the script or something
or some other random logic error interfering with things, like manipulating the audio source from another script
Print something in start and see if it shows more than once
and, generally, do some diagnostic work
it becomes.
audioSource.Play();
print($"audioSource.isPlaying: {audioSource.isPlaying}");
that's extremely strange
if it stays true, even as the audio clip gets loaded, then you are barking up the wrong tree
the problem is somewhere else
Strange, but exactly as I expect lol
so we thinking how to avoid it, even though the problem was not there
I am sorry @heady iris @quartz folio
understand the problem before you attack it (:
still I do not know where else the problemb can be :[
lemme change it to the void I guess
how can i make unity wait for example like this
Debug.Log("example")
//Wait 2 Seconds
Debug.Log("Done Waiting")
and yes, with Enumerator (for example)
private void Update()
{
if (audioSource.isPlaying)
{
if (!changingTime) timeSlider.rawValue = (int)audioSource.time;
ChangeTimeInputText();
}
else
{
print("Changed BG Music");
PlayBackgroundMusic();
ChangeTimeSlider();
}
}
private void PlayBackgroundMusic()
{
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
audioSource.Play();
print($"audioSource.isPlaying: {audioSource.isPlaying}");
}
I now have this and it always prints that audioSource.isPlaying is true. Still it is executed a few times.
and the GM with audioSource does also have DDOL script
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hi there, just interested if anyone had this problem before.
In unity, my game has not compiler errors, and everythings running as it should, but when I exported to a webgl build some of the coroutines didn't work at all
If you want to test the game for yourself and see the problem accures when entering a wild battle, here's the game link : https://jeffrygames.itch.io/hexmone
Usually stuff like this is caused by your code expecting:
- A certain script execution order
- A certain ordering of the arrays returned by functions like FindGameObjectsWithTag
neither of which are guaranteed
@magic parrot I thikn you have lot's of issues with colliders in your game
What do you mean?
player can climb on the walls and cannot go between doors
"That's not a bug, thats a feature" kind of thing
I am not sure those are features π
the wall thingy is, i am not sure what do you mean by walking between doors
if you mean the doors dont react, you need to press space or j to interact with them @gray mural
may I ask you why do you use this?
if (Input.GetKey(KeyCode.W))
{
// ...
}
else if (Input.GetKey(KeyCode.S))
{
// ...
}
else if (Input.GetKey(KeyCode.D))
{
// ...
}
else if (Input.GetKey(KeyCode.A))
{
// ...
}
I cannot go to the top right or bottom left
thats on purpose
just use
if (Input.GetKey(KeyCode.W))
{
// ...
}
if (Input.GetKey(KeyCode.S))
{
// ...
}
if (Input.GetKey(KeyCode.D))
{
// ...
}
if (Input.GetKey(KeyCode.A))
{
// ...
}
that's strange then
its because its suppoused to be like a retro pokemon game
i was investigating sudden lag spike after implementing a feature and it just editor loop taking up 95% of the usage, this should be fine to ignore right?
oh my, thats not good
its weird tho, my playerloop don't have anything executing for that long
Hello again guys !
I am using a Physics2D.Raycast to check how far an enemy is in a script of mine, following advice from this channel.
The raycast seem to find Trigger-colliders and Normal-colliders, even though I want only trigger-colliders.
I found the alternative signature public static int Raycast(Vector2 origin, Vector2 direction, ContactFilter2D contactFilter, RaycastHit2D[] results, float distance = Mathf.Infinity); which should let me filter to only Normal-colliders using the ContactFilter2D, but it uses an array of results. Reading the doc, it doesn't tell me, even though I think it's the most important point of the Raycast :
Is the array of results ordered by distance from the raycast's point of origin ?
The results are not ordered by anything
if you only want the first hit, don't use the multiple/array version
just use the version that returns a single hit
nvm something just choke the editor, restarted the editor its fine now
why isn't there a "normal" way of using it (with the public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);signature) that let you use only normal-colliders ?
There is
I'm not sure why it's not in the docs
my visual studio code tells me it doesn't exists :/
or rather, it didn't show it to me in the list of potential signatures when writing the beginning of the call, and when writing it totally, it gives me an error telling me that it "can not convert from ContactFilter2D to int" (because there is another signature with an int instead of the contactFilter2d)
Yeah you need a PhysicsScene2D instance to have access to the linked method
Not sure how and where to get one
I do not understand a word you're saying :/
@magic parrot sorry, how to leave or play?
what are PhysicsScene2D and the difference with Physics2D ?
It's for use with https://docs.unity3d.com/Manual/physics-multi-scene.html
Physics2D just does things in the default (single) physics scene
if you're using multi scene physics you need to specify which physics scene you want to do queries in - hence the PhysicsScene2D object
how do I get the physicsscene2D instance from my scene to do the raycast on ? (on a simple game)
Sorry I didn't realize the method I linked was only on PhysicsScene2D
seems like an oversight on Unity's part to not backport that into Physics2D
if I have a game with multiple scene, and load another scene when I change level, should I use this default thing ?
as long as you're not using multiple physics scenes it doesn't matter how many scenes you load
there's only the default physics scene
It worries me that it will work right now in testing because I only have 1 scene while debugging, but it won't work later when the player can win a level and go to another one :p
you would know if you were using multiple physics scenes