#archived-code-general
1 messages Β· Page 243 of 1
How do I check if smaller rectangles fit in a rectangle-sized area? Calculating areas doesn't work because the rectangles have different scales, and their rotation must remain the same. I also want these rectangles to be instantiated inside the area.
are the rects AABB?
you said the rotation is the same (though you can still rotate them to be two AABBs then check otherwise you need SAT)
Does anyone have experience with connecting bluetooth devices with Unity and getting data from the connected devices? I need some help with connecting a Sensor with the quest3
Don't cross-post. Choose one channel
sorry I dont know what AABB or SAT is. I said the rotation part because I dont want the objects to be rotated on instantiation
Sorry!
(Was not sure where to post..π
)
I'll stick to one channel from now,
but the rectangles sides are always parallel
Is everything I just said nonsense?
always parallel doesnt mean they are axis aligned (the width and height is aligned to x and y axis)
they are aligned on x and y axis
then easy, you have two rects and you only need to check if A.min>=B.min&&B.max<=A.max (min is bottomleft and max is topright) and you need to check then reversely after that since A may stay inside B
you can also change >= to >
okay. How do I get positions for the rectangles
the min of smaller rect will fall in special range in order not to go outside the big rect area
from big.min to big.max-small.size (calculated from max-min)
or restrict the max, the idea is same
I am not sure if I understood everything. Could someone provide example code?
i am not sure how to do it with multiple rectangles
Can they overlap?
i remember a long time ago we have a discussion on how to allocate (and deallocate) AABB space "efficiently"
but i doubt you cant understand it......(my idea is based on k-d tree and free list but i forgot how issue implemented it at the end)
another much simpler approach is to check if the new spawned rect overlaps with other old spawned rects
I was thinking if there is a asset for doing it
but this is not really that important for my project, I can easily change my level design
Does anyone know if an XML-Serialization based Save System works on Mobile (Android / IOS)
why would it not? XML is a string based format just like Json
I saw a post on a forum about it not working, thanks for the clarification
Do you know that C# .Net has a XML library build in?
Yea i normally use System.xml for handling saving in my projects. I was just wondering if there is anything that needs to be taken into account when it comes to mobile development
Nope, just make sure you save/load to Application.persistentDataPath
Okay perfect, thank you
hello!
is there any way to detect collision on spawn? i have a gameobject with a trigger collider that is instantiated and another object that detects the trigger and does some actions. the problem is that the gameobject that detects the trigger can sometimes be in a point where the trigger can be instantiated and there is no way to avid this. is there a way to check if it is colliding in the start function or some other trick to ignore collision with objects that are already colliding when created?
Have a look at the Physics.Overlap (for axis aligned primitives) and Physics.CalculatePenetration (for transformed colliders) API. You canβt use trigger callbacks if you want to check before instantiating.
Question:
The other day I opened a Unity project that wasn't mine, and in order to open it Unity told me that automatic recompilation of code was going to get disabled...
But now, when I open my project, code do not recompile if I modify it. How can I re-enable that?
I googled it, but in Preferences I did not find "Auto Refresh".
Probably moved then, look it up for your specific Unity version
Just found it's under Asset Pipeline in newer versions
Hello devs, i have question - is it possible to somehow use Vector2.dot instead Vector3.dot To reduce calculations ,bcs i have to much of them.
Calculation in X and Z axis is enough for me. no need of Y axis
Vector3 DirToTarget = Vector3.Normalize(transform.position - MainCar.position);
DotProduct= Vector3.Dot(transform.forward, DirToTarget);
what can replace Vector3.Normalize to pass it to Vector2.Dot?
thank you in advance
no, casting vec3 to vec2 discard the z
using System.Collections.Generic;
using UnityEngine;
public class jumpanim : MonoBehaviour
{
// Start is called before the first frame update
public Animation jumpanimation;
public AnimationClip jump1;
public AnimationClip jump2;
public float timer;
public float animno;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) { jumpanimation.Play(); }
if (Input.GetKeyDown(KeyCode.Space) && jumpanimation.isPlaying)
{
jumpanimation.Stop();
{
if (timer < animno)
{ timer = timer + Time.deltaTime; }
else
{
jumpanimation.clip = jump1;
jumpanimation.Play();
jumpanimation.clip = jump2;
}
}
}
if (jumpanimation.clip == jump1) { Debug.Log("anim2 playing"); }
}
}```
SOMEONE HELP why no anim playing but still no error
im rly rly new to coding
someone can fix it for me
you also dont need Vector3.Normalize(). You can just write it like so:
myVector.normalized;
You can use Debug.Log("Some Text"); to figure out what is being called and what isn't. Looking at it, you are probably playing the animation but stop it immediately afterwards. You might need an else if () for your second statement. I also recommend not writing your if statements in 1 line like that, makes it hard to read and miss these errors.
no animation is playing
it was working perfectly until i added this line
if (timer < animno)
{ timer = timer + Time.deltaTime; }
so after you increment the timer, where you decrease it?
As I said. Use Debug.Log() to figure out which if statements are being called.
wdymmm
i dont understand
please im insanely new to coding
i just watched a flappy bird tutorial and now im trying to add animations myself cuz the tutorial didnt have
your code:
if(t<T){
t+=dt;
}else{
nothing related to t here
}
more to the point, how often do you expect if (timer < animno) to be executed?
oh yeah
i thin k i understand
there is a problem that
the timer is going up
rly slow
how to fix it
its like 0.00001 and next frame 0.000002
i need it to go 1 per second
In Update() you check if the player presses Space and if he does you Play() the animation. But in the very next line you check again for Space and also if the jumpanimation.isPlaying is true. I assume jumpanimation.Play() would set jumpanimation.isPlaying to true, so when the player presses Space you Play() the animation but instantly call jumpanimation.Stop() as well.
But I don't know if this is the case or not. That's why you should use Debug.Log("Second If Statement") or something to figure out if my theory is correct.
you only increase the timer when the player presses space bar, so you would need to increase it outside the if statement
toggle a bool in the if statement, only increase timer if bool is true
like if its been 2 sec after pressing space play anim 2 and if its not then play anim 1
thats my goal
So,
if space -> Play anim 1 -> start timer
if timer > 2 -> Play anim 2
no nesting required
@fervent furnace will it work if i pass like this
DotProduct= Vector2.Dot(
new Vector2(transform.position.X, transform.position.Z).normalized,
new Vector2(DirToTarget.position.X, DirToTarget.position.Z).normalized);
@somber tapir like this?
DotProduct= Vector2.Dot(transform.forward.normalized, DirToTarget.normalized);
@somber tapir pardon for interruption
i doubt that copying the value is slower or the compiler can optimize it, though vec2.normalize should be faster than vec3 a lot.....
that wont even compile
how do i start timer and not just +1
if its in if state
c# is case sensitive
like you are already doing, add deltatime to timer
but it only goes up when i press space and stops, i need it to keep going after i press space and reset after i press space again
Well, looks fine (the second part), transform.forward is already normalized so you wouldn't need .normalized there.
so add to it outside of the if
but then it keeps going even if i dont press space
oh wait im dum
i understand
but wait
for the first space
like the first space hit the player does
i want it to
start the timer after that
timer = 0;
...
if (space) timer+= deltaTime;
else
if (timer > 0) timer += deltatime;
...
if (timer > 2) // Do stuff; timer =0;
or is that too advanced for me
nah this expects you to already know these basic concepts
o sorry
all gud π
this i think is what im already doing and this only adds value to timer after i hit space
like its at 0 and after each time i hit space it goes up by 0.01
note I have an else in there
it increments the time if no space has been hit but the timer has been started
@fervent furnace @knotty sun @rigid island what about this ? is there something that can be used instead transform.forward. maybe that all stupid but want to try
idk what ur doing lol I just saw this
it will compile if thats what ur asking
looks fine
those variable names suck tho
do you know if it possible to use Vector2 instead of Vector3 to increase performance. but need use Only X and Z
you are using a normalized direction as the second argument, that does not make sense for a .Dot calculation
i think unity just uses v2 as v3 with 0 out Z
since the engine is 3d
the perfomance is probably negligible
whats an extra 4 bytes..
yea, it will still work ok tho
i use too much of it in Update method, so tried to reduce calculations and get rid of Y axis in calculations .bcs game allmost top down space
there are probably other things I would worry about optimizing instead of simple structs
thats like saying i use too many floats
rendering and other stuff like that is more performance heavy
@knotty sun i think i did what u showed me and same issue is happening
show code
only 1 animation plays everytime
timer = 0;
if (Input.GetKeyDown(KeyCode.Space))
{ jumpanimation.Stop();
jumpanimation.Play();
timer= 0;
timer += Time.deltaTime;
}
else
{ timer += Time.deltaTime; }
if (timer > animno) { jumpanimation.clip = jump1;}
else if (timer < animno) { jumpanimation.clip = jump2;}
```
ok, the timer=0 needs to be outside the method
whats the purpose of this timer again?
huh what do u mean
well can i screenshare to show u
ok i see , if it occurs to much in profiling ,I'll back to this matter. thank you
or send clip
just give me a quick TLDR
wait let me send clip but it might look stupid im really new
whats that
cause seems you can use some sort of animation events
like in a few words just explain what ur doing
jump animation or something?
i want anim1 to play inside of 2 sec of pressing spacebar and anim2 to play if its been more than 2 seconds
in between the spaces
look it simple
float timer = 0;
void Update () { // Do the Rest }
you mean holding spacebar ?
errors are showing
no
are you doing a combo system
if player press space once and then presses space again in under 2 sec then play anim 1
and if player press space once and the next time after 2 sec thenplay other anim
@rigid island nah i just watched a tutorial to make flappy bird
it didnt have animations
i made my own
1 animation worked but it looks weird
if we press space fast
thats why i need 2]
ik it sound stupid
lemme try send clip
you really need to start thinking about your code
doesn't sound stupid just sounds like XY sorta problem
if i place outside void update
what is the error? that has no errors
if (Input.GetKeyDown(KeyCode.Space))
{ jumpanimation.clip = jump1;
jumpanimation.Play();
timer = Time.deltaTime;
}
else if (timer > 0)
{ timer += Time.deltaTime; }
if (timer > animno) {
jumpanimation.clip = jump2;
jumpanimation.Play();
timer=0;
}
still doesnt work though :((
hmm lemme try that
OKAY I THINK U SOLVED THE PROB
but like now
if i press jump before 2 sec it shows no animation basically delay of 2 sec before the anim shows
wait i think i can fix that tho
i think it might be cuz there is no animation stop
dam nvm still doesnt work
then add a if isPlaying -> Stop
where
i mean its the same problem as before
only 1 anim plays everytime
the timer only goes up when i press space
show your code
WAIT NVM TIMER IS GOING UP
but the anim still not playing
if (Input.GetKeyDown(KeyCode.Space))
{ jumpanimation.clip = jump1;
jumpanimation.Play();
timer += Time.deltaTime;
}
else if (timer > 0)
{ timer += Time.deltaTime; }
if (timer > animno) {
jumpanimation.clip = jump2;
jumpanimation.Play();
timer=0;
}
wait no thats not it
if (Input.GetKeyDown(KeyCode.Space))
{
jumpanimation.Stop();
jumpanimation.clip = jump2;
jumpanimation.Play();
timer += Time.deltaTime;
}
else if (timer > 0)
{ timer += Time.deltaTime; }
if (timer > animno)
{
jumpanimation.clip = jump1;
jumpanimation.Play();
timer = 0;
}
here
it plays jump2 everytime i hit space
but timer works perfectly
it resets if space after 2
so what is the value of animno in the inspector?
two
no, jump1 first then jump2
it doesnt matter tho its playing the same animation
also
huuuuuh what
it plays the jump1 automatically after timer hits 2
even if i dont press jump
then animno is not 2
it is 2
show me
wait lemme send clip of what happening
no, that is pointless
it loading
oh ok
then lemme just send ss
here u go
i know there prob a way easier way to do all this by directly doing rotations but i dont know how
right so the code says
start the timer if space is pressed
if the timer has started increment it
if the timer has reached 2 play the second anim
IDK IM NEW
stick to animator then
yes its doing that
i want to do it
so what's the problem?
if the timer has reached 2 AND spacebar is pressed
play 2nd anim
its doing it automatically
when timer hits 2
ah, so add another space check to the timer> anino if
Is there a way to see a class in the inspector without it being based from monobehavior?
yes, reference it in a Monobehaviour or use a ScriptableObject
yes use [System.Serializable] above the class declaration
I'm just kinda annoyed I have to type using static .... Every time I create a new class :/
why would you always need static ?
global variables lover
I have a script like this public abstract class something<T>: monobehavior if I create a nested class in it,it 'll get really hard to manage
XY problem
So I decided to the create class somewhere else
Hello y'all. In my game I have a level decoration editor that I'm trying to get up and running. Is it better to create a thread so I don't "clutter" this channel?
So I just use a using static classname to access to it
But every time I create a new class I have to type that it's get annoying
then make your own class template
It's not visible in the inspector
I assume they're talking about creating a class template inside Visual Studio
or whatever IDE you're using
static classes will never be visible in the inspector (?)
tbh if typing 1 line of code is 'annoying' then programming is probably not for you
its either that or you're doing that specific thing wrong (maybe using static stuff too much?)
steve there is new problem
I'm not Steve but drop the issue
you just said its static?
wait let me try to fix
when you ask a question you need to show the relevant code
is this in Update()?
No I'm just using namespace
yes
Alright, don't use Animation, right off the bat
then if you add the attribute I said, you can show regular POCO inside inspector
they can't be directly attached to gameobjects though
in the Animation window in Unity, just drag the animation clip "Bird" in there, and make a note of it's name
and just do jumpanimation.Play("Bird", -1, 0f); inside your script
This is much much less of a headache to work with
This is why I prefer using threads in this server. It's like a seperate lane on the highway from all this π₯²
i'll be so real I don't even know what qualifys as "beginner", "general" or "advanced" concepts
general IMO you are expected to know all this basic jargon
aight bet
i think 70% of threads here belong in #π»βcode-beginner
I think this would be good for like Procedual mesh generation and stuff like that
i hate 3D procedural generation. that involves so much math
Mimicing Unity's Transformation System at Runtime
I would say
Beginner - Doesn't know how to read or google
General - Knows how to read and google but can't be arsed to
Advanced - Knows how to read and google but still doesn't understand stuff
google becoming a lost art π¦
I agree, but Idk man. Google hates me today
apparently nobody on Unity Forums has attempted what I'm trying to attempt
indeed, if it aint a crappy YT tut it doesn't exist
but also using Unity Forums requires me to log into Unity ID. and I can't be asked to do that for the 13th time today
ever heard of cookies?
love cookies. Unity appears to not though.
Hey can you store a Touch as a object?
why cant you use whatever it is?
Touch is already an object
btw only saw ur thread for a second but axis == Axis.X) I would not use == for floats
its a enum :c
axis.x is enum?
that makes no sense
I'm trying to store different things as object and later convert it back,
hear me out
I don't know why I have a bug that I cannot set it
maybe put more information in your posts then
feels like there is some sort of misunderstanding going on
some code might help
you can store anything as an Object type and convert it back to whatever it was before you stored it
but thats circumventing they c# type system which is usually a code smell, but sometimes OK (or even neccessary)
Okay, so essentially I use an enum to differentiate the different arrow GameObjects and be able to know what axis they are controlling. Not sure why I didn't just use a string tbf but yes
I use that in order to know what property to just change
which part isn't working ?
where do you assign baseTUI
its not that its not working, its more like I'm unsure how to go about getting, and handling some of this input
is there any problem with having globals for WaitForFixedUpdate/WaitForEndOfFrame? I know potential issues with WaitForSecondsRealtime (it has the time counter inside so yielding from different coroutines will wait until the same time even if started at different moments - I can't say if WaitForSeconds works the same because unlike realtime version its code is native so I can't easily decompile it) but what about fixedupdate/endofframe?
Nothing wrong with that no
However make sure you are using EndOfFrame properly
so why does unity provide them as classes instead of just global yieldinstruction references?
Many people use it thinking it means "wait one frame" and it doesn't
I understand what it means
Poor design decision from 10+ years ago?
I have my own coroutine library that completely implements coroutines in editor
so everything that works in player works in editor as well
so I don't have to rewrite a ton of code that relies on coroutines to work in editor
- wrapper for unity coroutines that implements a ton of extra stuff
I was just curious about these 2 objects since I can't easily decompile unity coroutine code and I was wondering why they aren't just globals
if they are safe to yield from multiple coroutines
because other things you can yield from a coroutine include data
like WaitForSeconds
it makes more sense to just be consistent
if you want to make your own static fields to hold instances of the non-configured coroutine objects, then that's fine
the thing with it - waitforendofframe doesn't need to be class since it can be just global reference
if they don't really hold any data
Yes, it doesn't need to be
and safe to return
it's just consistenet this way
then it's a complete waste to have them as classes
and tbh I disagree with design decision with waitforsecondsrealtime, i.e. not being able to cache it
but w/e
i'm pretty sure you can reuse it
you can reuse but not while it's in use
I decompiled its code and it least in unity 2019 it will not work
ah, yes, it is mutable
because it stores time when it should stop waiting when you yield it first time and until it reaches that time it will not set new time
good to know that
not sure about waitforseconds, since it's native code but it's probably same
so basically you can reuse it in the same coroutine but it's not safe to reuse in multiple coroutines
oh that is curious
That's probably what I was remembering.
I was surprised one is native code and one is not
hey y'all
Honestly I'm just shit at math, but I'm trying to rotate my gameObject using a Z axis sprite that i'm dragging with my mosue.
This is the code for it:
void EditRotation(Ray camRay, float planeDist)
{
// Calculate the change in mouse position
Vector3 currentMousePosition = camRay.GetPoint(planeDist);
// Calculate the angle of rotation based on the mouse movement
float angle = Mathf.Atan2(currentMousePosition.y - initial.y, currentMousePosition.x - initial.x) * Mathf.Rad2Deg;
// Apply the rotation based on the axis
if (axis == Axis.Z)
{
Vector3 rotation = Thing.transform.rotation.eulerAngles;
rotation.z += angle;
Thing.transform.rotation = Quaternion.Euler(rotation);
}
// Update the initial position for the next frame
initial = currentMousePosition;
}```
But this is the result I get:
your code is computing the angle between your old mouse position and your new mouse position
then adding that angle to your current Z Euler rotation
that's wrong; that's like doing transform.position += desiredPosition; instead of transform.position = desiredPosition;
Instead, you should compute two angles
- The angle from the center of the object to the old mouse position
- The angle from the center of the object to the new mouse position
The difference between those two will be how much to rotate the object by
alright, thank you :)
You could get rid of the trig by doing this instead
Vector3 oldDelta = initial - transform.position;
Vector3 newDelta = currentMousePosition - transform.position;
float delta = Vector3.SignedAngle(oldDelta, newDelta, Vector3.forward);
SignedAngle gives you the angle between two vectors, relative to an axis
this might be backwards; in that case, negate the result or use Vector3.back
I almost never use trig nowadays :p
trigonometry my beloved
the Vector and Quaternion methods usually make it easier to see what the actual intent is
i was just going to go ahead and just use Mathf.Abs for no reason, but maybe this would be beter than my math :p
so the next line would be transform.rotation *= Quaternion.AngleAxis(delta, Vector3.forward);
euler angles can surprise you
although, in this case, it should be fine
you can have problems if you try to clamp them to a range
you might have seen all three euler angles change when rotating around an axis before, for example
i'm unsure whether to clamp the other axis honestly. I'm not sure if I should take such a decision. I'll test it with players later and see how "limiting" it could possibly be.
is there a way to force something that implements IMyInterface1 to also implement IMyInterface2?
like an extra constraint
nvm lol
you can't constrain to two types like that
interfaces can inherit from one another though, so if you have an interface that should also always implement another interface for example IUsableItem should also be an IItem then IUsableItem can inherit IItem
hi do you guys know the shortcut to reformat code spaces in visual studio
forgot shortcut key but its the sweeper icon at the bottom
cntrl K +ctrl E
if interface1 implements interface2, then does that force interface1 to make a concrete implementation for methods in interface2?
or does that pass it down to whatever class actually implements interface1
the responsibility is on the implementing type
ok, and if I have multiple interfaces, does that work out? like IA : IB, IC : IB, and class : IA, IC
I'm struggeling with a save system / main menu, anyone here have a minute to spare?
yeah
I have the data serializing/de-serializing
i have profile id's working
i'm stumped on the slave slot menu
trying to make the tutorial i am watching work with my main menu which is a little diferent.
and it's all so overwealming at this point i feel im in over my head
break this down a bit to a more specific problem
i'm honestly not 100% sure about this one, seems like it should work though
ok. well that's part of my issue is i'm so many steps in I'm no longer sure what step one of the problem is.
hold on let me think
you could make a single save slot a single serializable class, suppose it has an int for how far you are, and an int for save slot ID
using TMPro;
using UnityEngine;
public class SaveSlot : MonoBehaviour
{
// Serialized field to assign a unique identifier for each save slot
[Header("Profile")]
[SerializeField] private string profileId = "";
// Reference to the GameObject that is shown when there is no data for this slot
[Header("Content")]
[SerializeField] private GameObject noDataContent;
// Reference to the GameObject that is shown when this slot has data
[SerializeField] private GameObject hasDataContent;
// Text component for displaying the character's name associated with this slot
[SerializeField] private TextMeshProUGUI characterName;
// Method to update the slot's display based on the given CharacterData
public void SetData(CharacterData characterData)
{
// If there is no character data (null), show 'no data' content and hide 'has data' content
if (characterData == null)
{
noDataContent.SetActive(true);
hasDataContent.SetActive(false);
}
else
{
// If there is character data, show 'has data' content and hide 'no data' content
noDataContent.SetActive(false);
hasDataContent.SetActive(true);
// Update the text to show the character's name
characterName.text = characterData.Name;
}
}
// Method called when this save slot is clicked
public void OnClickSaveSlot()
{
// Notify the MainMenu to update the selected profile ID with this slot's profile ID
MainMenu.Instance.SetSelectedProfileId(this.profileId);
}
// Getter method to access the private profileId field
public string GetProfileId()
{
return this.profileId;
}
public void SetProfileId(string id)
{
profileId = id;
}
}
you can look through a file directory to find all the files of that type, and now you have several instances of files corresponding to save files
it is serializing the data correctly i can see it make save files in my dir
ok, but you need to populate a menu with save slots, and then go find it
I'm at the part where i want the save slot menu to activate when i start the game, and check if ther are save's or not.
like, a menu with buttons for slots 1,2,3. And if I click slot 2, you need to know to go get file2
you can make one file that stores information of which file goes to which slot, and open/edit it.
OR you can open all the files and store a bit of metadata in each
not quite, I want it to generate an empty save slot each time you go into the select character menu, but also generate any previously made profiles
like saveSlots.JSON, which could be like a list of (string filename, int slotID)
that detail isn't that important imo. What you need to do is effectively make a list of tuples of (string filename, int slotID)
once you make that list, then you can hand that off to the UI script, and do whatever the hell you want
but making that list of tuples is the first order of business
you could even parse that, with (myClass parsedClass, int slotID)
public class SaveSlotsMenu : MonoBehaviour
{
[SerializeField] private GameObject saveSlotPrefab; // Assign in Unity Editor
[SerializeField] private Transform saveSlotContainer; // Assign in Unity Editor
private SaveSlot[] saveSlots;
private void Awake()
{
saveSlots = this.GetComponentsInChildren<SaveSlot>();
}
private void Start()
{
// Get all save profiles from SaveManager
Dictionary<string, CharacterData> saveProfiles = SaveManager.Instance.GetAllProfileGameData();
// Create a save slot for each save profile
// Create a save slot for each save profile
foreach (KeyValuePair<string, CharacterData> profile in saveProfiles)
{
CreateSaveSlot(profile.Key);
}
ActivateMenu();
}
// Activates and populates the menu with data for each save slot,
// updating each slot with corresponding character data if available
public void ActivateMenu()
{
// Retrieve a dictionary of all profiles and their corresponding character data from SaveManager
Dictionary<string, CharacterData> profilesCharacterData = SaveManager.Instance.GetAllProfileGameData();
// Iterate over each save slot present in the menu
foreach (SaveSlot saveSlot in saveSlots)
{
// Initialize a variable to hold the character data for the current save slot
CharacterData profileData = null;
// Try to get the character data associated with the current save slot's profile ID.
// If successful, profileData is set; if not, profileData remains null
profilesCharacterData.TryGetValue(saveSlot.GetProfileId(), out profileData);
!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.
// Update the current save slot with the retrieved or default character data
saveSlot.SetData(profileData);
}
}
public void CreateSaveSlot(string profileId)
{
// Instantiate a new save slot from the prefab
GameObject newSlot = Instantiate(saveSlotPrefab, saveSlotContainer);
// Assign a unique profile ID to the new save slot
SaveSlot saveSlotScript = newSlot.GetComponent<SaveSlot>();
saveSlotScript.SetProfileId(profileId); // Assign the profile ID
saveSlots = this.GetComponentsInChildren<SaveSlot>(); // Update the saveSlots array
}
}```
hmm hmm. I need to walk through this from step one
including my main menu script
you should have a few classes
and find out what is happening. cus at this point ive just been following a tutorial and now im really confused lol
one class is the simple serialized save data. One class should be in charge of managing different save slot files (Writing to, openning them, reading them, organizing them...). One class connects that information to UI, and puts requests to the save manager to query contents or change save data
a single save slot class should NOT be a monobehaviour
@hard viper want to hop in a voice channel?
nty
I'm just pointing out that I think you need to break this up a bit, and that is why you are confused.
well, i have a save slot, a save slot menu, a data serializer, a character data, a save manager, and a main menu.
all different classes
well, what is the issue you are having?
i just need to walk through my scripts again and find the problem as it occurs. Sorry. Right now I can barely identify what the issue is. I dont understand how to get the save slot menu to work, that's generaly my problem. like i said data serialization is working, my save manager saves and loads data correctly. the problem is finding out how to get my main menu script, and my save slot menu script to play nicley togeather.
are save systems some of the most complex parts of game systems?
this is definatly the most coplex thing ive done. but this is my first game lol.
not really - They're quite simple. The harder part is making sure your data is organized sensibly in a way that is conducive to serialization and deserialization
and lining up your order of initialization of the game world when loading a save
Anyone happen to know what this person is talking about in this thread?
https://forum.unity.com/threads/cursor-cant-click-in-locked-mouse-state.1171457/#post-8355120
I got my button working with FPS cursor locked but now the cursor is showing and flickering.
πΏ
Don't you hate when in unity you have to fight against the engine for such basic stuff π¦
are you saying you don't know how to decide if a save exists in a certain save slot?
or that you don't know how to write data to a specific save slot?
as you see the cursor is locked and worked on UI but custom Input module is making cursor visible/flicker
hmm maybe this is #archived-code-advanced problem..
Only way I was able to fix it is to copy-paste the underlying code of GetMousePointerEventData, ProcessMove, and ProcessDrag into that custom FirstPersonInputModule (instead of just calling the base methods), then removing the code that disables functionality when Cursor.lockState == CursorLockMode.Locked.
No idea
are you using the FirstPersonInputModule?
I copied it yeah its custom
no idea why now my cursor is visible and flickers (im guessing its fighting visible = false)
is the script the same script linked in the forum? guess i could take a look through that i guess
they said Only way I was able to fix it is to copy-paste the underlying code of GetMousePointerEventData, ProcessMove, and ProcessDrag into that custom FirstPersonInputModule
but this is what exactly says in script
the script is exactly the one from thread yes

just tryina get my windows XP working ingame π¦
maybe this could be a layer issue..? If you're using SpriteRenderers or, UI, Canvas, something maybe force the OrderOfLayer up?
idk how would layers fix it .. I think its something to do with overring the cursor lockstate somehow.. not sure why
I'm not quite sure. Unless you're setting the activity of your cursor with the cursor lockstate, maybe it could help..?
basically sometimes Unity just acts weird if stuff is on the same layer sometimes. I don't know I've always just had to seperate a bunch of my objects in layers otherwise issues just happen
my canvas is in WorldSpace which is why i had to get a custom FPS input module because it doesn't like events for UI when cursor is locked
upgrades it to windows 11
that would be a "downgrade" π€£
who knew OS would eventually be spyware and bloatware
why does Windows 11 constantly catch strays, this is crazy π
after initial bloatware uninstall its fine :c
i hate this engine
macos > linux > windows
but seriously its so frustrating having to fight the engine's poor design for this stuff ..
you missed cpm > macos
Does anyone know why using Scale is just... being weird?
Basically, I use two arrows to change the scale OR position of a target. It depends on what mode I'm currently in. The axis I use are X and Y.
I also use 1 ring on the Z axis to change the rotation of the target.
This is the scale function, which works correctly if I haven't changed the rotation of the target:
void EditScale(Ray camRay, float planeDist)
{
// Calculate the change in mouse position
Vector3 currentMousePosition = camRay.GetPoint(planeDist);
float delta = currentMousePosition.y - initial.y; // Use the y component for vertical movement
// Calculate the scale factor based on the mouse movement
float scaleFactor = 1f + delta * ScaleMultiplier; // You can adjust the multiplier based on your preference
// Apply the scale based on the axis
if (axis == Axis.X)
Thing.transform.localScale = new Vector3(initial.x * scaleFactor, Thing.transform.localScale.y, Thing.transform.localScale.z);
else if (axis == Axis.Y)
Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, initial.y * scaleFactor, Thing.transform.localScale.z);
else if (axis == Axis.Z)
Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, Thing.transform.localScale.y, initial.z * scaleFactor);
// Update the initial position for the next frame
initial = currentMousePosition;
}```
a relic!
However, if i rotate it, using this function:
void EditRotation(Ray camRay, float planeDist)
{
// Calculate the change in mouse position
Vector3 currentMousePosition = camRay.GetPoint(planeDist);
// Calculate the rotation angle based on the change in mouse position
Vector3 oldDelta = initial - Thing.transform.position;
Vector3 newDelta = currentMousePosition - Thing.transform.position;
float delta = Vector3.SignedAngle(oldDelta, newDelta, Vector3.forward);
// Apply the rotation based on the axis
if (axis == Axis.Z)
{
Thing.transform.Rotate(Vector3.forward, delta);
}
// Update the initial position for the next frame
initial = currentMousePosition;
}```
Then, it just stops working. After rotating, if i try to drag an arrow, it just goes to the opposite side of the object. Here's the visualized issue:
tf is CPM, clicks per minute OS?
its like a 70s OS
children
im fifteen leave it be π
small child
it isnt even my fault. i like old things
like uh
ok no its not old but its annoying because its old
assembly
6502 assembly specifically
< big child at 30 π₯²
i cannot imagine being thirty years old. it just sounds like something that just happens
its all downhill from there xD
nah
we get wiser but our body hates us
Control Program/Monitor and later Control Program for Microcomputer
CPM is just task manager?
CPM is what drives your windows computer if you did but know it
vroom vroom?
is tht not TPM? or am i thinking of the other thing that my computer just randomly has for no reason at all
No, it is not TPM
Having to lock a player just to control UI in FPS will be so ugly... why can't unity just allow this to work..
https://youtu.be/qQDM8AX8mOY?si=pTV4qSjosPmtMG5H how do i make something like this? the exact same thing. no modifying stuff nothing. just the exact same. im planning on making the entire rhythm heaven (i mean does anyone even know that game..?) saga in unity.
The game that started it all.
hopefully better music..
yeah there is better music
quality
[ENGLISH RHM]
Gameplay "perfect" of this game: Rhythm Heaven Megamix for 3DS.
-Minigame: Karate Man Returns! (Perfect). Enjoy.
-Description of Minigame: More karate training! We've got
an all-new song and all new stuff
to throw at you! (No practice)
and also better sprites
yea
this game is on all versions on rhythm heaven
lemme show you the best one
find a way to match the BPM
Rhythm Heaven is complex, but its indeed doable. And in a less annoying fashion than Nintendo's shitty engine
I hate how they ruined this song, the original version is soooo much better than this.
or use an audio analyzer and get the frequencies to determine where you want the hits (usually peaks like Kicks or Snares)
dynamic games do similar when you have custom tracks (ie AudioSurf, BeatHazard)
create an animation that throws objects out
spawn the objects on 60/(bpm) (and if you want, multiply that value by 1, 2, 3 or 4 to wait a certain amount of beats per throw)
but this is super important, minus the time it'll take to get to the player too, so that it'll get to the player on TIME
im not like an expert or anything im sorta a beginner
so i dont understand stuff
just send a tutorial
yeah ik
i thought this was for any type of unity gamemakers sorry
anyways lets move there
I guess would it be better just raycasting onto a collider on screen to determine if you're on UI interaction and only then enable the FirstPersonInputModule ?
Seems like ugly workaround , if anyone knows a better way I'd love to hear it
In Unity 2022, how can I get the current NavMeshLink that an NavMeshAgent is traversing?
The NavMeshAgent.currentOffMeshLinkData.owner is only available in >= 2023. In 2022 there is NavMeshAgent.currentOffMeshLinkData.offMeshLink but that is for OffMeshLink, bot NavMeshLink. ΒΏHow do I get the second one?
not a code issue, but the answer is to stop using collab and switch to plasticSCM instead (or some other version control)
was your google not working?
next time don't skip the first result that tells you how to turn it off form the Services window
but this is still not code related
mb
how would you instantiate a gameobject at the point of a particle colliding with a gameobject in the scene?
OnParticleCollision
I've tried something like this:
private void OnParticleCollision(GameObject other)
{
List<ParticleCollisionEvent> pColls = new();
system.GetCollisionEvents(other, pColls);
for (int i = 0; i < pColls.Count; i++)
{
GameObject acid = Instantiate(acidPool, pColls[i].intersection, Quaternion.LookRotation(Vector3.forward, pColls[i].normal));
acid.transform.parent = gameObject.transform;
acidPools.Add(acid);
}
}
however the code ends up killing performance
well
you're creating a new list every particle collision
thats already huge garbage
and also how many particles do hit ?
I've got it set to 30 total
btw see how unity caches the list
can't you just do
public List<ParticleCollisionEvent> collisionEvents = new();
yes
try cache first then keep iterating and profiling
also check how many are hitting
one time I had a blood splat that would draw decals on each splat, I ended up making thousands for some reason because forgot to delete once it hit
if this alone is killing performance, then you probably have more than 30 particles or 30 things being spawned
and also pool your acidPool (funny sounding)
dont use Instantiate
if you want perfomance
pool?
is it possible to make custom audio effects that I can add to mixer groups?
I know I can add effect to source with OnAudioFilterRead but is it possible to do with mixer group like built-in effects
if I want to apply effect to all sources in a mixer group
Perhaps. But it might require writing it in C++
There's another result that seems promising if you Google custom dsp effects for unity.
seems like another thing that unity promised and never delivered because I can't find anything other than onaudiofilterread
unity native api doesn't seem to have anything other than some really basic stuff
Hey guys. I am trying to position a line renderer the same origin and direction as my raycast. When the child object of the VR rig is at 0/0/0 it lines up correctly as you can see in the image (the blue line inside the green line is the ray being logged). However, when the object moves up and down the the line stays the same but the ray moves up. Does anyone know why this is happening? Here is my code.
Ok, is it from an asset (i assume this is the case)? Did you make the class?
One script by its own can be an asset, but ok. I assume you mean you created the script.
Open the script, do you see a namespace?
yeah
You're really making it hard to help lol.
Yeah what? There is a namespace?
Can you show the script maybe?
Show where the error is coming from? Do you have errors in the compiler?
"Can you show the script maybe?"
Screenshot the ide, don't crop it at all
Do you have FaskIKFabric anywhere in your own scripts?
If you do, do you have using FastIKFabric; at the top?
no
Well, without getting complete information, all I can say is that either there are compiler errors, or you are trying to use FastIKFabric without using the namespace.
The file name and class name seem to match, and that is all I was able to confirm
the line renderer needs positions.
You're giving it a position and a direction
an appropriate position here would be like:
returnPosition.position + returnPosition.forward * 5
I figured it out and that is exactly what i did tahnks π
this isnt unity
Then it shouldn't be in this Discord
just figured this was extremely general code and game-dev code specific. if you feel like it somehow is not productive, feel free to remove it i guess.
internet mods are wild in their reasoning skills
yeah it's wild that the Unity discord only takes Unity questions
Anyone know why my texture comes out black?
:\
if (newTex == null)
newTex = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBAFloat, 8, false);
Graphics.CopyTexture(renderTexture, newTex);
met.mainTexture = newTex;```
I was reading here its the better way to grab texture from Rendertexture since it lives on GPU
https://forum.unity.com/threads/rendertexture-readpixels-getpixel-shortcut.1103338/#post-7101430
Is the RenderTexture marked as isReadable?
enableRandomWrite = true; when you create it
I tried it, still doesn't put RT on texture :\
happens on android only ? try change the depth stencil format to D16-something(forgot which one)
yeah, thought it was android, had similar issue awhile back and that fixed it
not sure what I could be doing wrong :\
Try with 0 (or -1) mipmaps just to see if that affects anything
And some other texture formats like RGBA32
Though it looks like it should work
tried both, same result
i read 3 threads and all said the same, I just copied
yeah basically If i change color formate I get this
then i have to go on this thread I found that tells me each format group π
I have used this, try itcs public static Texture2D RenderTextureToTexture2D(RenderTexture renderTexture) { RenderTexture activeOriginal = RenderTexture.active; int w = renderTexture.width, h = renderTexture.height; Texture2D tex = new Texture2D(w, h, renderTexture.graphicsFormat, 0); // I had 'Texture2D tex = new Texture2D(w, h);' but you probably need the format here RenderTexture.active = renderTexture; tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); tex.Apply(); RenderTexture.active = activeOriginal; return tex; }
I will try it. I was just wary because of that thread said ReadPixels is expensive since it has to put data from gpu back to cpu
Yeah it's probably not very fast, I used it to save a rendertexture to a texture2d as a sub asset
So it needs to be on CPU
I was going to use it almost every second or less continiously :\
Try it just to test, maybe it will give some clues on what's wrong
will do!
would this be it ?
private Texture2D RenderTextureToTexture2D(RenderTexture renderTexture)
{
RenderTexture activeOriginal = RenderTexture.active;
int w = renderTexture.width, h = renderTexture.height;
Texture2D tex = new Texture2D(w, h, renderTexture.graphicsFormat, 0); // I had 'Texture2D tex = new Texture2D(w, h);' but you probably need the format here
RenderTexture.active = renderTexture;
tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
tex.Apply();
RenderTexture.active = activeOriginal;
return tex;
}
private void Start()
{
newTex = RenderTextureToTexture2D(renderTexture);
yield break;
}```
the code is nearly identical to what it would be in a unity script, and the problem it solves is very common for beginners to face in unity. it harms no one and is relevant enough that it can only be helpful. a reasonable person would go "yeah that's not exactly unity, but anyone doing unity game dev could benefit from looking at it or give a solution that could help unity users reading it.". It is weird for you to be so fussy about this
there are not many game dev servers
thats why i went here for help
Something like that, see my comment tho, not sure if that line is right, I just edited it blindly
Or replace the format with whatever you want
But try that first and see if its still black
still black
stanford prison experiment
it worked for you with render texture?
Yes but I create my rendertextures from script
Ahhh..
the Start method
it don't likie
put it in Update and it works
so maybe the other thing works too..
wow..cannot believe it was this simple..
2 hours gone
ty @quartz folio @craggy veldt @hexed pecan
apparently It needed to be in at least Update and not Start..
Makes sense, Start runs before Update so your RTex hasn't rendered yet
yeah still getting familiar how the gpu renders π
You could probably just WaitForEndOfFrame from Start and then do the texture copy
So that it renders first
crazy cause it was a Coroutine start and that woul've been perf
To be clear, you can make Start a coroutine
Oh yeah I had it like that but changed to void after thought coroutine was messing with it
Oh, sorry, misread
all good !
really intellisense..??
you couldn't tell me this 2 hours ago
wtf happening
Hello! just asking if I save via player prefs, do I need to save it on firebase too? or other database
if you want like cloud save or something?
what are you trying to accomplish
yes, we have login and registration via firebase but have used player prefs for coins and shops, will it be saved for specific user who have logged in?
or should I connect the player prefs saves on the authentication?
playerprefs is saved locally on the device
you should keep that stuff in server if you don't want it messed with (coins and shops )
if you want it somewhere else, it needs to go somewhere else
An online game with currency definitely needs to save currency in the cloud somewhere
What if we don't have an online purchase? but just simple shop where the user can change their characters if they buy
Their bought characters when they log out, will it still be there when they logged back in? or the number of coins they have
We only store it via playerprefs
okay! Thank you so much! π
Anyone knows how to fix? It only print ok good 1 and line 41 have a null reference
T is Touch
Does that mean Touch cannot be stored as object?
i tried to cast list<int> to list<object> in online compiler and it gives error directly, i dk why in your case your code still run....
The as operator returns null when the cast is not valid
Whatever that thing is it's not a baseTUI<object>
it even give out an error, and i have no idea why his code doesnt result on any exception
This looks like a console app mixed with unity.
Where's the Unity part...
Hello, I'm trying to make Steam Achievement. but it said Steamworks is not Initialized.
The error is inside function TestIfAvailableClient()
InvalidOperationException: Steamworks is not initialized.
Steamworks.InteropHelp.TestIfAvailableClient () (at Assets/com.rlabrecque.steamworks.net/Runtime/InteropHelp.cs:34)
Steamworks.SteamUserStats.GetAchievement (System.String pchName, System.Boolean& pbAchieved) (at Assets/com.rlabrecque.steamworks.net/Runtime/autogen/isteamuserstats.cs:72)
AchievementManager.Start () (at Assets/__Source/Scripts/AchievementManager.cs:76)
I already have steam running, logged in with account that has the game, edit steam_appid.txt
what else do I miss?
more info is needed.. like did you wait for it to be initialized before doing something
ehh no. It was on Start() and it was the first scene. I'm trying to get achievement with Steamworks.SteamUserStats.GetAchievement(genericNames[id], out bool local_AchievedStatus);
how do I wait? are there callback from steam that will tell me if it's ready?
show how you Init
I think i didn't... initialize anything.. (?)
This is the only script that ever touches Steamworks related thing in the entire project.
hmmm well I'm not sure why are you attempting to use Steamworks.SteamUserStats.GetAchievement without initializing the client
hmm.... looks like it's because I'm a lazy idiot. I was following this tutorial but missed the part that said attach the SteamManager script to a GameObject in your starting scene.
So, youβre working on your Unity game and youβre getting ready to release it on Steam. But the Steamworks API can be intimidating. Itβsβ¦
you got it working ? π
i just usually look at the documentation
I'm not sure if it's working yet, but it doesn't throw error anymore.
I usually also look at documentation but for some reason I didn't do that this time. Probably because I got intimidated by this, and then proceed to find tutorial to hold my hand.
I'll read this for now. Thank you for the reminder. Now I'm gonna go hit myself with a broom.
Hello, I have a code block as follows.
Everything is working correctly but "ConnectionApprovalCallback" is never called, what could be the reason?
NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.OnServerStarted += OnServerStarted;
NetworkManager.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.OnTransportFailure += OnTransportFailure;
NetworkManager.OnServerStopped += OnServerStopped;
A) Don't Cross Post
B) How on earth do you expect a sensible answer based only on that information?
C) #archived-networking
A) Okey
Also, my question is very logical. Each delegate works, one does not work, these delegates are related to each other.
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval/
you are supposed to assign it, not add to the delegate
Is there a way to load an AudioClip without a coroutine? I need to load a .ogg on disk and i want to do that through a function to make it easier to use, doesn't matter if the game freezes for a bit
you could use tasks instead of coroutines
async void Start()
{
// build your absolute path
var path = Path.Combine(Application.dataPath, "Audio", "sounds", "myAudioClip.wav");
// wait for the load and set your property
CurrentClip = await LoadClip(path);
//... do something with it
}
async Task<AudioClip> LoadClip(string path)
{
AudioClip clip = null;
using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.WAV))
{
uwr.SendWebRequest();
// wrap tasks in try/catch, otherwise it'll fail silently
try
{
while (!uwr.isDone) await Task.Delay(5);
if (uwr.isNetworkError || uwr.isHttpError) Debug.Log($"{uwr.error}");
else
{
clip = DownloadHandlerAudioClip.GetContent(uwr);
}
}
catch (Exception err)
{
Debug.Log($"{err.Message}, {err.StackTrace}");
}
}
return clip;
}
That could work, thanks
where can i find good c++ plugins? i want to try to avoid using unity's physics
@ocean river
lol
you know what happens anyway?
lemme read the code then
ok
so is this script activated when you want to change skin or something
cause that script will only execute once if it starts
oh ok
im not too intermediate myself just saying
I'm new on code
maybe try doing Debug.Log() and see if it even reaches that code
okay let me see
ye it logs
sorry cant help you with 2d or playerprefs
Okay
but that means enableselectcharacter is disabled
isnt activated?
yeah idk try changing it i guess
- I'd like to get the logarithmic rolloff curve from audio source without having an instance of audio source. I.e. some way to make one on the fly, through a constructor or a static method. Anything on this?
bezier curve? no idea
Hey y'all, I have an issue where, after rotating the object with the circle, trying to scale it up with the arrows gives a weird 'flipped' result.
I don't know if it is because my calculations are weird, but this is what I'm experiencing:
This is the function to scale up, and this is put on a script that is on each arrow:
void EditScale(Ray camRay, float planeDist)
{
// Calculate the change in mouse position
Vector3 currentMousePosition = camRay.GetPoint(planeDist);
float delta = currentMousePosition.y - initial.y; // Use the y component for vertical movement
// Calculate the scale factor based on the mouse movement
float scaleFactor = 1f + delta * ScaleMultiplier; // You can adjust the multiplier based on your preference
// Apply the scale based on the axis
if (axis == Axis.X)
Thing.transform.localScale = new Vector3(initial.x * scaleFactor, Thing.transform.localScale.y, Thing.transform.localScale.z);
else if (axis == Axis.Y)
Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, initial.y * scaleFactor, Thing.transform.localScale.z);
else if (axis == Axis.Z)
Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, Thing.transform.localScale.y, initial.z * scaleFactor);
// Update the initial position for the next frame
initial = currentMousePosition;
}```
Let me know if you need more code, but I'm bad at math and honestly don't know why this is happening π₯²
Don't you want to measure mouse movement along the direction the scale handle points in?
You're measuring vertically
also, you're using initial.x, initial.y and initial.z when calculating the scale
that doesn't make any sense
how would i make a draggable object, collide with a rb2d, but not move the rb
so you want the object to get stuck on objects, but not be able to actually push them
yes
I think 2D physics let you control whether rigidbodies apply force on a per-layer basis
I'm pretty sure I saw that before, at least..
Does Queue have a contain function?
is there a reason you can't just try it? sounds like you already have a queue :p
Ye i am
But im trying to find the return value rn
And like how to make it work so I thought id find like those site that contain the functions parameters
But I cant find one for some reason
here's the documentation
For C# stuff that isn't Unity-specific, the Microsoft .NET documentation is what you want
One thing to watch out for is that some stuff only exists in newer versions of .NET
ones that Unity doesn't support yet
In this case, it's fine; this class has existed for ages
but I know that PriorityQueue isn't available to use in Unity, for example
(very different from a regular Queue)
I think you should be recording the cursor position when you started scaling the object
and also record the original scale
then, every frame, compute the delta and use that to compute a scale factor
and then set the current local scale based on that delta and the original scale
public string SelectRandomScene()
{
string selectedScene = null;
while (selectedScene == null || sceneQueue.Contains(selectedScene))
{
selectedScene = PlayMaps[Random.Range(0, PlayMaps.Count)];
print(selectedScene);
}
Enqueue(selectedScene);
return selectedScene;
}
public void Enqueue(string value)
{
if (sceneQueue.Count >= maxQueueLen)
{
sceneQueue.Dequeue();
}
sceneQueue.Enqueue(value);
}
Sorry Im having a bit of a fever rn and maybe my brain is not braining but is there smth in my code that might cause an infinite loop
sceneQueue always starts with one element inside and the maxQueueLen is vurrently at 2 so Enqueue shouldnt break anything
And rn there is no error
It just freezes the game
always bound the loop if you are not sure
bound?
int iteration=100;
while(true&&--iteration>0){
work;
}
oh ok
basically, give up if it's stuck
Ye let me try it
I would suggest logging whatever is going on
Ok so i found out whats the issue
But im not sure why it is
For some reason sceneQueue.Contains always returns true even if the element I randomly selected is not in there
Hi guys, I have a dialogue system in my game for npcs and it works like when distance is 2.5m or less and I press E it should pop up dialogue according to NPC Im talking to but for some reason distance keeps being 0 and when I press E it doesnt do anything. Here is DialogueManager script: https://hastebin.com/share/izoziwepew.csharp and here is NPC script: https://hastebin.com/share/ulaxoyekak.csharp
have you actually logged the contents of the queue?
Yes I found out why
another group member used the function elsewhere
So it caused an infinite loop since currently we have 2 maps only
And they both got loaded into queue
Yeah, you should add a safeguard for that
If the number of available maps is less than or equal to the number you want to keep in the queue, throw an error
What's the most efficient logic for when a menu has for example 14 items but only 10 buttons, when you scroll above the max number of buttons all the buttons change the item they hold. Like an inventory
Vivox is an offical unity package tough
I'll need to add some force along the rigidbody x-axis to the player for wall jumping, but my code for acceleration and deceleration is interfering with this. Any ideas?
Full code. I'll trying to do this with AddForce function, but that shit doesn't want to work
You can use a cooldown/timer that activates when you walljump. When that timer is active, don't override your velocity
If you still want some control while the walljump timer is active, you can use AddForce, or velocity with MoveTowards
does anyone know what is causing this when I try to move my player? I think its because of rigidbody but Im not sure...Here is FPS controller script and video so you guys can see better whats happening:https://hastebin.com/share/tupiyoyezu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Send video in mp4 so we can view it in discord
problem is that this video screen recorder only lets me record in wmv
no option for mp4
@icy herald It's not very complex, have you made a timer before?
yep, but i think there is a much better solution for this
What's that?
There is not as far as I know. You can apply current velocity, but that has issues
You need to halt setting velocity in order for the addforce to work. A timer would do that. You could do a coroutine as the timer too.
If you have better solution, use that I guess
I can describe whats happening if u dont want to install video if u would like?
Sure
You should describe it even if we see the video
okay sorry
What issue do you see with this way of doing it?
so when I press any key to move(W,A,S,D) my character doesnt move he leans in that direction and he will then eventually fall...here is a pic when Im holding W:
Rigidbody inspector -> Constraints -> Freeze rotation X+Z
- how to get ITilemap
Argument 2: cannot convert from 'UnityEngine.Tilemaps.Tilemap' to 'UnityEngine.Tilemaps.ITilemap'
thanks it works
is there a way to make a tile sprite by composition? Like a tile which is the sprite for two tiles overlaid on each other?
Yeah, we gave that to them already. They are on 2021 which doesn't have that
Alright
And I said I would find the best solution =D. I'll just use a variable to control "isWallJumping" and if it's equals true - just stop invoke movement method.
also i used another jump method for jump button holding, to use another x force and y force
Lack of understanding on our part due to lack of clarity on yours.
Yours is an event based timer essentially. We didn't know the purpose of the addforce π€·ββοΈ
yep, another time i would add more info for my requests
i got a question, but first : "does anyone knows php ?", if yes my question could be more easily understood
in php you can evaluate something and choose bewteen two "things" depending of the result
somevar ? takeThisIfTrue : takeThisIfFalse
is there something similar in c# ?
exactly the same
ternary operator
yes it is, i didnt know it existed in c#
in some languages i had to make a function to imitate its behaviour
But it isn't as simple as a ? b : c
Seems like the same thing that was suggested but you use a bool instead of a float timer.
tell me
You'd want an if statement over a ternary if that was your only goal. Ternary was meant to be used as var d = a ? b : cwhere there is a need for a return value
i would like to use it inside a new vector to avoid making many lines
Yeah, you can use it in a vector constructor
yep, and using bool instead of a float timer much times better =D
because depending of a enum im switiching what value to pick
Single line statements shouldn't be a goal but since you're using the return value, it'd be fine.
When do you set the bool to false?
its also for my brain 
but ty for the tip
Found my issues with the stupid scaling thingy just a second ago after actually reading my code :3
Okay, does anyone know how to calculate the mouse delta, relative to the current axis i'm moving, while also relative to the current rotation of the obejct?
For example, this is an object at 0 on the Z, and the blue arrow is facing the right way. I can calculate the delta correctly on the z using:
if(axis == Axis.X)
delta = currentMousePosition.x - initial.x;```
But as soon as i go 180 on the Z, the blue arrow faces the left way. The delta is still being calculated correctly, but I know that I need to invert the delta.
I don't want to hardcode this every 90 degrees, as this would just be inaccurate. So... how would I handle this?
true then im jumping, and false in all other, like if grounded, if roof above him and if jump button released
(The empty lines you edited in just made it harder to read IMO)
sorry i just don't like sending super huge chunks that are easy to get lost in π₯²
transform.position = new Vector3(
(_movement == SpeedTextMovement.playerX ? _player.transform.position.x : transform.position.x),
(_movement == SpeedTextMovement.playerY ? _player.transform.position.y : transform.position.y),
transform.position.z
);
this was the goal
(a lot of other things will be added in the futur so rn its quite simple
Should probably avoid comparing floating point values
?
its an enum
0.1f == 1f/10f can yield false
well SpeedTextMovement is an enum so i am not comparing floats ?
wait, Unity doesn't apply Mathf.Approximately to the comparison? weird
Unless playerX and playerY were assigned said values specifically and not calculated.
Pretty sure it's for vector comparison and not float
It's an enum apparently
I see what you mean, I did the exact same thing and everyone was freaking out that I was comparing floats π₯²
i would never compare floats. I don't know in what situation I would ever need to do that anyway
Ah, the naming convention got me..
how do you guys name an enum ? just curious
or is it the "speed" that made you thought it was a float
_movement really doesn't sound like an enum either
if (fish == Fish.Catfish)
...```
In this case Horizontal and Vertical
i give you that
I have one for determining what Axis a certain script moves
so using Axis.X, Axis.Y and Axis.Z makes everybody cry
i wanted to keep it short for know
Could use a Dir/Direction suffix or something
Nvm that could be a float as well lol
when really, I just don't want to compare strings. I want to use fancy dropdowns in the editor.
well this script is for my eyes only so if i can understand it im fine ig
Unity can't. float isn't a data type provided by Unity.
Every call to the position property of Transform will return a new Vector 3. An alternative to this is to cache and modify a single Vector 3 then reassign it back using the position property.cs var position = transform.position; if (_movement == SpeedTextMovement.playerX) position.x = ... if ... position.y = ... transform.position = position;
Could probably cache to bool results for x and y as well and avoid any of the operations above.
Anyone know this, for some reason Reading Colors on my new texture made from RT is not working(only reads 1 color and its gray?)
Any ideas what could be the issue ?
The colors are properly read on my other color texture
Sorry I don't understand, wdym
this one?
I'm pretty sure you can use any type you want -- I see you picked Color32 there
It's possible that's the wrong type for your texture
its a TextureFormat.RGBAFloat, is that different ?
Definitely
Color32 is 8-bit RGBA
So you're trying to reinterpret 32-bit floats as bytes
It'll give you gibberish
Color might work
since that's RGBA 32-bit floats
unfortunatly var pixelData = newTex.GetPixelData<Color>(0);
just give me black
same 1 element tho
Color might not be a valid choice at all
is there anyway to convert this texture to rgb8
sorry yes, the one on the left is the Texture I made from Render texture
newTex = new Texture2D(
renderTexture.width,
renderTexture.height,
TextureFormat.RGBAFloat,
0, false);
Graphics.CopyTexture(renderTexture, newTex);
Try asking for floats and see if the values make any sense
if I dont put RGBAFloat there CopyTexture gives mismatch error so thats not an option
so this is not the render texture you're copying from
that's just a texture you had that works correctly
I meant the one on the left
sorry
ahh wait..Maybe this ?
https://docs.unity3d.com/ScriptReference/Graphics.ConvertTexture.html
That would let you change the format, yeah
If you want to keep using Color32, that's your way
RGBA32 SFloat should be four 32-bit signed floats
(big!)
yeah, 128*128*16 is 262KB, and I guess mipmaps add some extra size
so i would need to use sfloat ?
If you want to use Color32, convert it to whatever has been working for you so far
I'm a little unsure about interpreting RGB8 as Color32, though.
I suspect that's going to give you the next pixel's red channel in the alpha
hopefylly nothing gets smashed xD
then the next entry in the native array will be GBRG, then BRGB, then RGBR, ...
GetPixelData doesn't care what the actual encoding is, AFAIK
It just reinterpets the memory as whatever type you give it
That's why you got this funny color
Ahh
is this really correct either?
notice the random alpha values
the order also doesn't make sense to me
yeah the alpha noticed were strange
but maybe cause im only using 1 of the pixel and prob grabing an edge where its like Filtered or some weird effect in unity
like Filtering
If you just want color data, without worrying about the format, use GetPixels
or you ran out of bounds
but that should throw an error
Actually, did you calculate an offset into that big 9-color image?
Oh yeah, that's exactly what happened
Notice how dark gray has a low alpha
Red has 100% alpha
Green has 0%
You interpreted RGB8 data (3 bytes per pixel) as Color32 (4 bytes per pixel)
there might have been enough extra space for that to work out mostly correctly
did i have to ? all the code I did is in the link
oh, right, you sent code
π«
okay that makes sense
I was wondering how you didn't go out of bounds at the end
So you grabbed RGB from one pixel and R from another pixel
and interpreted those four values as RGBA

Is there a reason you can't just use GetPixels?
It's slower, I guess
but that would get around this hackery
is this wrong format?
var newtex = new Texture2D(
renderTexture.width,
renderTexture.height,
TextureFormat.ETC2_RGBA8,
0, false);```
I don't know a lot about texture formats tbh
TextureFormat.RGB24 sounds like it would match your existing data
I think thats what I was reading, because i need to preform this action at least once a second or less
but you're also interpreting the existing data wrongly
so it's a wash lol
you could make structs that store either bytes or floats in the correct order
you might need to add attributes to make the compiler respect the layout you specify
I was gonna do the hacky way and just put all their alphas to 1 xD
then you could ask for pixel data in the appropriate format
Depending on the image size, this could cause a bunch of other garbage colors to appear
imagine you get to the border between two colors and you're not aligned correctly
public struct ColorRGB {
public byte red;
public byte green;
public byte blue;
}
I'm mainly trying to average these colors if thats makes sense
I forget the attributes you need to force this to be laid out exactly as specified in memory
haven't done that before
of course, reinterpreting the colors yourself is probably just as expensive as letting Unity do it
although, I guess you can avoid allocating an array
yeah these colors thing is confusing as hell
well, you're trying to directly interpret texture data
and there are a lot of ways to store texture data
just remember that you will not get an error for using the wrong data type with GetPixelData
because it takes nativearray?
well, not strictly
but it is true that NativeArray is a way to directly expose native memory to your code
It only works with unmanaged types, because you don't have the C# runtime keeping track of references and stuff
It's like reinterpreting a char * as an int * in C
same memory, different view
would be better if I just use ReadPixels?
https://docs.unity3d.com/ScriptReference/TextureFormat.html
im trying to read through these but its just getting more and more confusing lol
i'd just use GetPixels and profile it
interesting: you can't use GetPixels on a crunch-compressed texture
will do that actually
hmm any reason why I would get 90000
public static Color[] ReadPixelColors(this Texture2D texture)
{
Color[] cs = texture.GetPixels();
for (int i = 0; i < cs.Length; i++)
{
cs[i].r = cs[i].a;
cs[i].g = cs[i].a;
cs[i].b = cs[i].a;
cs[i].a = 1.0f;
}
return cs;
}```
I can't even scroll it crashes the window editor xD
I have a problem with my AI movement system. I recently rewrote my movement system to physics based, because when I moved the characters with transform they bugged across obstacles. I solved this issue with physics but when I have a lot of characters instantiated the game instead of lagging, gives higher speed to all characters moving with physics. Does anyone knows how to fix this?
//Update
private void Update()
{
//Get All Enemies
List<GameObject> enemies = new List<GameObject>();
enemies.Clear();
Component[] humanoids = Humanoids.GetComponentsInChildren<Component>();
foreach(Component hum in humanoids)
{
if (hum.gameObject.CompareTag("Enemy"))
{
enemies.Add(hum.gameObject);
}
}
//Get The Closest Enemy
if (enemies.Count != 0)
{
Target = enemies.OrderBy(enemy => Vector3.Distance(transform.position, enemy.transform.position)).FirstOrDefault();
Vector3 TargetDirection = (Target.transform.position - transform.position).normalized;
//NewPosition
Vector3 newPosition = lastPosition;
//Move Towards Target (Physics)
newPosition = TargetDirection * Speed * Time.deltaTime * 100f;
if (Vector3.Distance(transform.position, Target.transform.position) > 1f && Vector3.Distance(transform.position, Target.transform.position) < 30f)
{
rb.velocity = new Vector3(newPosition.x, rb.velocity.y, newPosition.z);
}
else if (Vector3.Distance(transform.position, Target.transform.position) >= 30f)
{
animator.SetBool("IsMoving", false);
return;
}
//............
//LastPosition
lastPosition = newPosition;
}
else
{
animator.SetBool("IsMoving", false);
}
}
my unity build caps frame rate to 60 FPS. is there a way for me to get some metric to see how much time is left between frames in dev build?
Unity Profiler
it does
Do you want it capped at 60?