#archived-code-general
1 messages · Page 70 of 1
My VR game keeps freezing every 4 seconds then unfreezing after a half second and I can't figure out why it is happening. I am using Unity URP and just put in an XR Origin (VR). It seems to have started when I put an XR Origin in the project.
By the way this is running on a Meta Quest 2
(Actually Oculus Quest 2 but I don't think it matters)
Use the profiler to see what's taking so long.
You should be able to setup a remote profiler with a development build.
I just heard of the profiler yesterday, so I don't really know anything about it
https://developer.oculus.com/documentation/unity/unity-profiler-tool/
https://developer.oculus.com/documentation/unity/unity-profiler-panel/
https://docs.unity3d.com/Manual/profiler-profiling-applications.html#:~:text=For a platform to appear in the Attach to Player drop-down it must meet the following requirements%3A
that's what the manual is for
yeah I know that, but I haven't had time to look over it.
Little headache here, I want to store a reference to an object (that is serialized), but I want it to be assigned null by default. I found that I can use [SerializeReference] which seems to do the trick, unless the property is not null and the script was reimported. Ideally, I'd like that to reset back to null. In this scenario, I don't need to serialize the property, it's just elsewhere the object does need to be serialized. Any ideas how I can reliably default it to null?
Not clear. By default, the value is null for [SerializeReference] and any other nullable object.
Yes, but when it isn't null, and a reimport occurs, it appears to lose the reference and it becomes an empty object rather than null. I dunno.
If you don't need it serialized why are you using SerializeReference?
An empty object would be equals to null. What I think you have is a value that is not correctly serialize.
Hello, I have a 1 MB text file and would like to load it and parse it to a serialized class. The text file is a JSON string.
https://hatebin.com/wikazkpgye
The following code only prints a very small portion of the file content.
How do I retrieve, save and parse the entire JSON data?
File.ReadAllText
Even that returns the same portion
then that is the entirety of your file contents.
hmm, maybe some quote got added while saving the json
will check
thank you
@leaden ice I just checked, the file loads fully on my editor but doesnt on my android device
using File.ReadAllText
how did you check
i copied pasted the txt file from my android phone to my pc
and loaded the file
it printed the entire text in my console
but when i try to load it in my editor and try to check it in adb logs it doesnt print everything
any idea why? @leaden ice
ADB / logcat might have a limit on log length
ahhhhhh
hahaha
thank you
will check if the json loaded properly
with the serialized class
ty again
alternative to EditorUtility.OpenFilePanel for player builds?
@leaden ice lmao, thanks alot man, turns out the log wasnt getting printed but the data exists
was stuck on it for an hour haha
ty again
Trying to access Unity's update loop inside of a static class. I don't want to use a monobehaviour entry point.
updateFunc = TestUpdateLoop;```
This doesn't give me any callbacks so I'm assuming I'm using it wrong, I just can't find any examples on the internet
It is not logic what you are trying to do.
You stuck the value of PlayerLoop.GetCurrentPlayerLoop().updateDelegate inside updateFunc than override the value of updateFunc for TestUpdateLoop.
I've practically never used delegates before
Can someone help me with a bug? The camera is messed up
I do not know how exactly to achieve what you want because I have never done it. (It does not seem like a good idea anyway) But you could look into:
https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677
https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.SetPlayerLoop.html
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/
AFAIK, there is no built-in way of doing that in a build, youd have to create your own, though its not overly difficult if you largely use the System.IO namespace, specifically System.IO.Directory, System.IO.File, System.IO.FileInfo and System.IO.Path, maybe System.IO.DirectoryInfo if you may want to show extra info about the folder as well, it would be easier to simply display a list and generate a prefab to throw the data of the folder into, a bit harder to show thumbnails or calculate something like file size, as the larger the folder, the longer it will take to do those calculations - alternatively, there are likely several assets on the store that have already done the majority of the work for you
Alternatively, you can look if there is usable native library that implements such functionality for your target platform such as
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog?source=recommendations&view=windowsdesktop-7.0
You could also try to see if you can use directly the application of your target platform like: Process.Start("explorer.exe" , @"C:\Users");
A little help please I am trying to use addressable for my project and wanted to know do I have to use unity cdn or it doesn’t matter and I want to know if I have two different projects how would I go about have user b create a project with all its assets and creat addressable and have user a load that cause I have my team working on different part of the game. Just want to know what would be the best way to handle this
- You do not need to have CDN for the usage of Addressable/AssetBundles
- And, if it is not necessary, try to keep your whole project in one. You should be able to orchestrate the different member of your team without needing two projects. The usage of well defined naming convention and workflow documentation could help it such enterprise.
For the sharing of Data/Source between multiple project, it should be done with the help of Package or Version Control. Addressable are not made for such use case same if they could work.
yeah our project is getting really big so would like to devide up the project
Thats a good point, if the platform is not Windows, then another alternative over System.IO may make more sense, though you may need some way of getting a callback if you launch a process like "explorer" - I didnt think you could use WinForms API in Unity, I remember looking into it at one point, though it was years ago by now
thanks a lot for the info!
im having trouble implementing a gun that shoots two lazers at one press ive got one to shoot but the other wont. i have two firing points with the same script attached to it. im my head this should work fine.
\
I'm pretty new to Unity, and semi-new when it comes to c#.
I have been trying to figure this out for about six hours, and I'm not having any luck, even after typing the problem out and talking to my rubber duck. I scoured the internet as best as I could.
My goal is to set an unused number between 0,9 to an instantiated object (button), use that number to pull the rest of the variables from that object when I click on it, and then populate some text boxes with those values. These objects will be destroyed and leave gaps to be filled occasionally.
But, my problem is that I don't know how to set the number to a prefab from outside of it, let alone make a function check that the index number is free before assigning it. And after that, I don't understand how to use the number to tell me what instantiated object (button) I have clicked on. I feel like it might be a simple problem, or maybe not, but my mind just can't get around the issues at the moment.
If someone can help, I'd appreciate it.
You're trying to set values to a prefab when the game isnt running right?
Like when you click a button in the editor?
The values are being set when it's instantiated while the game is running-via code.
When I click the button while the game is running.
Get the gameobjects, get a reference to their class instance, set the variables.
I don't understand what you're struggling on.
For the buttons, you'll need to get their references, and subscribe to the onClick event
If you don't understand how to get a gameobject's reference, then you should be in the beginner section.
If you don't know how to make a function, then you should probably start learning C# instead of asking people to write code for you
Show us the script
Code for playerGun: which is attached to BOTH firing points: https://gdl.space/olajavisuy.cs
Code for my Lazer: https://gdl.space/sanigawizo.cs
Both firing points are probably set to the same one
Can you show me your hierarchy and what you referenced in your script
I know how to make functions, and reference details of game objects through GetComponent. Maybe I just don't know how to use the OnClick function in the Unity well enough. Probably should've thrown this in beginner, like you've suggested, sorry about that.
Thanks for trying to help 😊
You just said in your original post that you don't know how to set values
I meant that I didn't know how to set only unique values to objects. I can set values fine, I just don't know how to check for existing values and provide one that doesn't exist between that 0-9 range.
And to ones that are instantiating from a prefab.
You should set the values from a singular source, for this problem. That would be the easiest
Do you have 10 prefabs at the time you want to assign them values?
And does it have to be a unique number within 0-9
You can either use a static class with the RuntimeInitializeOnLoadMethod attribute, or you can create a mono class and put it on a singular empty gameobject, which then instantiates and assigns values to the objects
Or have a static class only containing an integer, and have each of your objects assign themselves a value from that static class, while iterating the static value.
They're created one at a time. And they don't 'have' to be between 0-9, but there will only be a maximum of ten of those objects at once.
For some reason line 25 doesn't work, I'm not getting any errors and I think everything is attached correctly
And add a seperate check if you already have more than 10
or you know, just don't use GUIDs in the first place
Why are you against Guids?
Because they have no purpose for this problem
Thanks for helping. I'll try to tackle the problem with your suggestions in mind, and I'll make sure to learn more before asking for help in this channel again.
The way I see it he wants to give every object an ID
I'm aware
Sounds like guids
Becomes hard to guarantee the uniqueness of ints when you start using multiple threads ;)
Why would you ever need multiple threads for this
Just start simple. Have a static class that contains an integer. Make it unsigned if you want. Doesn't matter right now.
When each of your gameobjects spawn, run Start() code that pulls up the static class and the integer inside of it. Apply that integer to the object itself, and then iterate it using ++. That would be the easiest way to go about tackling this problem.
Doesn't matter, you said they don't fit for the problem but by saying this you've clearly showed that you are against GUIDs regardless of the problem
Even unity themselves consider them a valid option for giving IDs to objects, as they use it in their samples
lmao
There is absolutely zero reason to use GUIDs for this.
Want to assign each gameobject's ID to an array slot? Not going to happen with GUIDs.
Not going to work if you use the same system for unsigned ints either
But you could just use a hashmap for this anyway
I think the problems of using unsigned integers are worse than the GUID problems
what arguments going on here
GUIDs vs unsigned integers for object IDs
i see
I am the author of a rollback netcode engine in development for Unity. It does not work without properly baking IDs into gameobjects.
I think I know what I'm talking about.
Again, you are creating problems when using GUIDs for this.
You also are not going to compress a GUID in any sensible manner
I have written my own encoder for my data compression
this was an amazing chain of events
not my problem that you reply with lmao
once someone comes out with a proper argument
See if you maybe read my messages, like I just read your message about the compression of ints, then maybe you'd understand
But as you said
Oh right, generating a random massive number that you can't compress or assign to a buffer index is better than iterating up
argument is over.
we're done here
Please configure your !ide to help with the issue.
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Guids would have been the best solution for this
Regular integers that iterate up with each object works too, but requires more code to set up to get the next number, especially when persisting data. Guid is as simple as calling guid.NewGuid(), not to mention it's not predictable. I doubt any of that matters, but it's definitely better when it comes to setting an id.
Also this conversation is stupid
Give your own solution but and don't bash eachother
Did you manage to fix your problem?
The setting of IDs, at least. I've got some other stuff to try and get working now, though. As is the way it goes.
That was to try give it a null value, which in my understanding isn't easily achievable in non UnityObjects.
What I want to do is I have a ScriptableObject that contains a list of Connector. In the EditorWindow, I want to keep a reference of a Connector, but it should default to null but instead it defaults to an instance of Connector. Hence the SerializeReference. Let me know if this isn't ideal.
Sorry, complete disagree. Absolutely no point not to use a direct ID mapped to an array index. You can reuse the IDs and keep it limited to a pretty small binary range. Dude literally said earlier that he wanted the IDs mapped to the GameObjects. This is a direct lookup. No point teaching pointless behavior while he's learning. These things are 128 bits each. I doubt anyone here will go over the UInt16 or UInt32 range on a single machine for entity IDs.
Any reference type in C# is null by default. It is quite easy to achieve. Unity's serialization is the only context in which that's not the case
So again I'll ask why you're serializing it if you don't need it serialized
As my ScriptableObject contains a list of Connector, wouldn't I have to serialize the Connector class in order for it to be saved with the ScriptableObject? That's why it's serialized, and in my editor window, I want a nullable Connector property that can have one of those connectors from the list.
@thin aurora he knows as he made his own encoder is and a famous author of a netcode rollback engine
What's your problem?
(I am just playing around, there are reasons why you'd use an int over guids like the one you provided)
Hey I am using unity's input system and I am wondering how I make so that as long as the jump key is pressed it will keep calling the function Jump
You can change the jump input from trigger behavior press to hold or you can switch a "jump" bool on when you press down and switch it off whenever you release the jump button.
I tried but it only calls the jump functions once (assuming when pressed)
i have Debug.Log("Jump Pressed");
inside the jump function just to make sure it's being called
You can make a new input called something like jump on release and use the bool option
it might be easier with the delegate route youve taken. I usually use events with the new input system.
oh this is getting annoying tbh
i have a script to iterate through my items to change something
i have a lot of them so im not doing it manually
it changes the scripts on the prefab
but the changes arent registering for some reason
i call PrefabUtility.RecordPrefabInstancePropertyModifications(item.gameObject);
that should record all changes right?
i also tried recording changes for the component that I changed but that didnt work either
the funny thing is it does work but when i reload unity it undoes it
instantiating before reload has changes applied
but selecting the prefab either shows changes applied or not depending on if I double clicked
and the thing is, i did the smae thing to mass add LODs and it worked fine
how would i have these visible inside the unity inspector but not editable
[Header("Movement")]
private float forwardSpeed;
private float backwardSpeed;
private float sidewaySpeed;
You probably need a custom editor for that
There's a library that has more attributes for the editor (I forgot the name), maybe that one has a solution
Either way, exposing them makes them mutable
No one can, at least yet. But in the case you ask a real question, maybe.
can someone teach me how to implement bobbing for my fps character?
I explained, not sure if you caught the message as it wasn't a ping, but I think I found a solution. Inside my editor window I changed [SerializedReference] to [NonSerialized] which seems to work, even though the Connector class is serialized for use with a ScriptableObject. It now starts off as null, and also goes back to null when the scripts are reimported. Not 100% sure why it goes back to null, I'd rather it remember the same Connector but this is better than broken so I'll take it. 🙂
i have this in my uiController
{
ghostAmount = amount;
// Update the ghost text
ghostText.text = ghostAmount.ToString();
Debug.Log("Ghost Amount: " + ghostAmount);
}
public void SetTime(float seconds)
{
time = seconds;
// Update the time text
timeText.text = time.ToString("0.00");
Debug.Log("Time: " + time);
}```
but it isn't updating my ui
i have a simple if for testing purpose to make sure everything connected right
{
uiController.SetTime(-1f);
}
if (Input.GetKeyDown(KeyCode.G))
{
uiController.SetGhostAmount(-1);
}```
but ui not updated
ia have my full code here: https://hatebin.com/hqquuwybsv
Your UI controller is a monobehaviour. You cannot define it with as a new object, it has to be a component on a GameObject you reference.
yes i changed that
void Start()
{
uiController = FindObjectOfType<UIController>();```
So as I said the whole time the solution is not to serialize it in the first place
I thought you were referring to the class itself, not the property in all honesty. I also didn't know you could use [NonSerialized] on a [Serialized] class 
I'm having some issues with raycast and tag exclusion. Here's my code:
[SerializeField] private float LaserRange = 8;
[SerializeField] private string[] ExcludedTags;
private GameObject circleInstance;
public GameObject circlePrefab;
public LayerMask blockingLayers;
private void FixedUpdate()
{
RaycastHit2D hit = Physics2D.Raycast(transform.GetChild(0).transform.position, transform.right, LaserRange, ~blockingLayers);
Debug.DrawRay(transform.GetChild(0).transform.position, transform.right * LaserRange);
if (hit.collider != null)
{
//Check every tag
for (int i = 0; i < ExcludedTags.Length; i++)
{
if (!hit.collider.CompareTag(ExcludedTags[i]))
{
Debug.Log("Is not excluded!");
// If the circle instance doesn't exist yet, create it
if (circleInstance == null)
{
circleInstance = Instantiate(circlePrefab);
}
if (!Input.GetKey(KeyCode.Mouse1))
{
// Update the position of the circle instance to match the point of contact
circleInstance.transform.position = hit.point;
}
}
}
}
else
{
// If the raycast doesn't hit anything, destroy the circle instance
if (circleInstance != null && !Input.GetKey(KeyCode.Mouse1))
{
DestroyLaser();
}
}
}
I added ExcludedTags strings in the Editor and checked if I've not misspelled any of them. When the raycast touches a GameObject with excluded tag, the circlePrefab is still being instanciated. Any ideas?
I'm currently trying to make a basic 2d spaceship, and so far(with the help of unity answers), i've managed to make this:
// Update is called once per frame
void Update()
{
Vector2 horizontal = Input.GetAxisRaw("Horizontal") * transform.right;
Vector2 vertical = Input.GetAxisRaw("Vertical") * transform.up;
float rotation = Input.GetAxisRaw("Rotation");
Vector2 inputVector = horizontal+vertical;
FireThrusters(inputVector, rotation);
}
public void FireThrusters(Vector2 movementDirection, float rotation)
{
Vector2 finalThrust = Vector2.zero;
//Apply Movement
foreach(var thruster in thrusters)
{
//Movement
float dot = Vector2.Dot(thruster.transform.right,movementDirection);
if(dot >= fireThreshold)
{
thruster.GetComponent<SpriteRenderer>().color = debugColorActive;
float participation = dot/fireThreshold;
Vector2 thrust = thruster.transform.right*participation*maxThrustForce;
finalThrust += thrust;
}
else
{
thruster.GetComponent<SpriteRenderer>().color = debugColorInactive;
}
}
rb.AddForce(finalThrust);
rb.velocity = Vector2.ClampMagnitude(rb.velocity,accelerationlimit);
}
}```
This works really well, however, It does not account for rotation. How can I check which thrusters should "Fire" to get my desired rotation, and then rotate using addtorque, ideally in a similar mannar to the code above? I used this: https://answers.unity.com/questions/923915/determining-thruster-activation-on-3d-spaceship.html link for what I have so far.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Your logic is wrong. You're instantiating for every tag that doesn't match. You want to only instantiate when NO tags match right?
Yeah
but there's the (!hit.collider.CompareTag(ExcludedTags[i]))
don't instantiate if the tag doesn't match
still no clue why my uicontrollerdoesnt update the ui while showing the value of the variables
Think about this situation
Excluded Tags is A and B
Object 1 has tag A - So will pass when checking excluded tag B
Object 2 has tag B - So will pass when checking excluded tag A
check all of the tags first, then do the rest of the logic of NO tags were found. A bool is your friend for this
does anyone have a 3d vr no clip script that uses trigger to use
thanks, I'll try some things
on my canvas i have the uicontroller, but my gamecontroller reference cant find it ``` private UIController uiController;
void Start()
{
uiController = FindObjectOfType<UIController>();```
Hi! I want to create a sync method that allows to get data from a local server. This code does work, but I can't it why is it so slow. For simple curl command the response is instant, but using my code the response takes a few seconds. How do I make it faster?
private string MakeCustomRequest(string endpoint, string type)
{
var task = MakeCustomRequestAsync(endpoint, type);
return task.GetAwaiter().GetResult();
}
private async Task<string> MakeCustomRequestAsync(string endpoint, string type)
{
using var request = new HttpRequestMessage(new HttpMethod(type), addrBegin + endpoint);
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(config.User + ":" + config.Password));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = await httpClient.SendAsync(request).ConfigureAwait(false);
var toString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Debug.Log(type + " " + addrBegin + endpoint + ": \n" + toString);
return toString;
}
i dont get it
object in scene with script
the right tag
uiController = GameObject.FindWithTag("UIController").GetComponent<UIController>();
NullReferenceException: Object reference not set to an instance of an object
You haven't shown that you're using the right tag.
How do i use the NetworObject.TrySetParent funktion corectly when i use it it gives me an error saying that its a group Methode and it cant be set
Hey all. How do I loop through every int in a float, then loop through every decimal in the same float? Couldn't find anything on this on Google.
What does "every int in a float" mean exactly?
Likewise for "every decimal in a float"
duh
Every whole number in a float, every decimal in a float.
Nevermind, I think I figured it out.
Int in float maybe like this:
5.15
7 <--
1.9
6 <--
9 <--
Yeah but maybe thats what he means
https://hastebin.com/share/omolekivig.csharp
Why might I be getting SendMessage cannot be called during Awake, ChechConsistency, or OnValidate (Brock: OnSpriteTilingPropertyChange)?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not sure, but try narrowing it down
-- delete 'OnValidate' first, and if it persists, this means it's because of the 'Awake' method
Hi all may i ask a question?
I have a textfile that gets updated by a python script.
Unity reads the text file, however Unity also locks it which prevents python from updating it since it cant append to the text file
anyway around this?
ah. that sucks
it does
I have a question too.
I cant get skeleton to work from a fbx, that i exported from maya 2022.
everytime i boot the game on my 3ds, it crashes after the logo.
only when i have the skeleton model loaded.
Read it into memory and release the file handle
i mean, model with a skeleton.
This is not a Unity issue it's your code issue
but its unity for 3ds...
No, it's normal for this to happen. The proper way is to set up a localhost port and sync there from python, read there from Unity
unity locks the file, i cant even manually update it since the resource is busy
Are we talking about gameplay? The editor? What?
except -- what are you wanna use that file for?
What's the context here
you boot the game on nintendo 3ds?
its very simple, i have a textfile. lets say test.txt and it contains text 1234
I ready the file (on Update) as follows: (works fine)
public void ReadString()
{
string path = "C:/Users/ZZZ/My Code/ZZZ/data/collections/ZZZFinal.txt";
StreamReader reader = new StreamReader(path);
//Read the text from directly from the test.txt file
coins.text = reader.ReadToEnd();
reader.Close();
}
however if i open my text file i cant make a change since resource is busy, which makes sense, but unity never "releases it'.
do i make a coroutine or something , maybe unity releases the lock?
You're reading the file every frame? Why
you’re reading the file like this…in update?
yea just as a test, it needs to update live
🕵️
its not a game btw
This is insanity
And it's no wonder unity always has a file lock on it
the text file updates every second XD
you’re reading the file every frame and wondering why the resource is busy
yea i knw
im asking whats the best way to unlock, since it does work at times
yup!
This ^
makes sense i guess ill look into it thanks
It's definitely OnValidate but I don't know why it's happening
Can anyone help with this?
Thanks mate got it working, this is a way better solution now need to spend time to flesh it out..
the bright blue box is a child of the dark blue box. the dark blue boc is connected to the orange box with a fixed joint. when the orange box(its gonna be a car) moves they should all move but the light blue box also has physics(because its the player) should still be able to move by itself and rotate wich would create a offset but right now the light blue box does not move at all when the dark blue box moves.
how could i solve this ?
Does anyone know how to fix this blur in camera?
Hey, how does WaitForSeconds works with very short times (close to time per frame)? I want to write each letter one at a time without it being frame dependant
it's never going to happen on the exact time (or just extremely unlikely)
Alright that explains a lot. Cos I was playing a sound according to that but the sound wasn't consistent
Hi everyone, i have a question. Im making a top down game where, to attack, the player
has 4 triggers 1 above, 1 below, 1 on the right and 1 on the left, and i want that when an enemy
gets inside of one of them (im using OnTriggerStay in the enemy's gameObject), and the key in the respective
direction gets pressed (im using GetKeyDown) a boolean called invincibility turns false
(which when its true, makes thefunction of recibing damage inside of the enemy
(called in update) not execute) once, for 1 frame, and the enemy's health gets reduced
by 5 (they have 20 health)
Should PlayScheduled in advance
what happens is that sometimes it works well, but sometimes it doesnt gets called
What is or are the reason this is happening? and how to solve it?
Can you get an int from an enum even though there are none defined?
i lost my temper
im trying to use physics2D.raycast to check for the enemy(which has a box collider2D before you ask)
and it wont detect it
oh?
wdym not defined?
you could just cast it
int myNumber = (int)myEnum
Is there anyway to store game data in application memory instead of file memory
Like the file memory stored using json
It can be accessed by the user and modified
I don't want that
Is there any other proper way to store data?
just store the file remotely..
i have a UI thing on my cameras canvas that tracks a scene object.
i do "myCamera.worldToScreen(myObj.position)" which works generally.
but when i move the camera, the UI object jumps/is wobbly while trying to stay at the correct position.
cant wrap my head around why that would happen. anyone else had a similar problem?
the camera-object ray is marked red in the scene, so thats not where the jumping comes from.
positioning happens in Update(), i tried lateUpdate and FixedUpdate too but all have a similar problem
Tried everything but it still persist.
I also tried someone elses code and it had the same issue
can someone tell me how to get child of a game object with script?
you couldn't just google this? also it belongs in #💻┃code-beginner
alr mb
Hey guys, can someone help me with a basic formula... I have 2 vars, lets say MaxX= 1000 and Maxy= 100. (x,y). I have to other vars x and y both = 0. In the update I have the x/y both increasing. I need them to both reach their max at the same time. How do I determine the amount I increase them both by?
This is easy stuff.. But I have been building websites for awhile and been away from game coding and math for awhile lol.
(MaxX / time) and (MaxY / time) per second respectively
time being the amount of time the animation should take in seconds
Untested :p
float MaxX = 1000f;
float Maxy = 100f;
float x = 0f;
float y = 0f;
void Update()
{
float Increment = (MaxX - x) / Maxy;
x += Increment * Time.deltaTime;
y += Time.deltaTime;
if (x >= MaxX && y >= Maxy)
{
// Do something
}
}```
I think..
I'm not sure if this is code, but I want to be able to decide which scenes are the levels, and the order that they are in. I was going to do this by having a SerializeField Scene array on my player, so that I can just drag them in, but it says that the type Scene is not supported. I also tried an array of SceneAssets which does let me drag them in, but I can't figure out how to load the Scene given a Scene Asset. Does anyone know of a different way to do this?
explain further wdym which scenes are levels
I mean that I have a lot of scenes in this project, but I don't want the player to play through every scene becayse some of them aren't levels, some of them are levels to play through, but others are things like test scenes where I just try to get something to work.
wdym go through all of them
don't u want a specific scene?
why do you need to "go through all of them"
could use something like this instead: https://dbrizov.github.io/na-docs/attributes/drawer_attributes/scene.html
i dont understand i made static instane variable still cant acces my class
[SerializeField] private TextMeshProUGUI ghostText;
[SerializeField] private TextMeshProUGUI timeText;
private int ghostAmount = 0;
private float time = 0f;
private void Awake()
{
ghostAmount = 3;
time = 1f;
if (instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}```
private UIController uiController = UIController.instance;
Sorry, I'm not really sure how to use this. I tried copying the code in, but I'm getting this error:
The type or namespace name 'SceneAttribute' could not be found (are you missing a using directive or an assembly reference?)
Thanks!
well yes, it's from the NaughtyAttributes package so you obviously need that installed into your project
oh I see
i also have my script attached to a object
but when trying to acces it i get error again
whas line 24
on GameController
{
uiController.DecreaseTime(1f);
}
if (Input.GetKeyDown(KeyCode.G))
{
uiController.DecreaseGhostAmount(1);
}```
increase and decrease time
uiController is null
show where you've assigned uiController
void Start()
{
// Set the initial game state
GameManager.State = GameState.MainMenu;
Debug.Log("Game controller update ruunning: " + "Update() method running");
}
void Update()
{
CheckGameState();
TriggerPause();
CheckGhostAmount();
CheckTimeAmount();
if (Input.GetKeyDown(KeyCode.T))
{
uiController.DecreaseTime(1f);
}
if (Input.GetKeyDown(KeyCode.G))
{
uiController.DecreaseGhostAmount(1);
}
}
uh
you shouldn't assign it in the field initializer, if both objects exist in the scene at edit time then the field initializer will likely run before Awake has been called to set up the singleton
shouldn't this error
the instance variable is static so no, it's just null at that point
oh tru
how is it null tell me
if instance is static why not just use that , or is it there benefit to cache to private var
or just make it a property
private UIController uiController => UIController.instance;
or get a proper reference to the instance instead of making everything into a singleton
pff, what a headache connecting two classes
what you mean i'm using it or not?
they mean don't use uiController just use UIController.instance everywhere you need it, don't need to stick it in a variable
ya more of a general question, is there a benefit(besides less typing I guess) over doing this instead ^
void Update()
{
CheckGameState();
TriggerPause();
CheckGhostAmount();
CheckTimeAmount();
if (Input.GetKeyDown(KeyCode.T))
{
UIController.instance.DecreaseTime(1f);
}
if (Input.GetKeyDown(KeyCode.G))
{
UIController.instance.DecreaseGhostAmount(1);
}
}
hmm I guess I answered my own, reading on this it
"every time you access the static instance CLR has to lookup the reference to static instance in memory"
yeah, reference to a reference?
wonder if this is true
Caching the static instance into a variable might make sense in certain cases where you need to access the static member multiple times within a method or across multiple methods, and you want to avoid the overhead of repeatedly accessing the static member from the class's metadata. However, this is typically a micro-optimization, and should only be done after profiling has shown that it's necessary.
it absolutely is a micro-optimization, the performance difference is negligible at best. gimme a few moments and i'll throw together a benchmark to prove that
i'd say it'd be very quick since it should still be in the cache
on this. so true right here as well
In general, it's usually better to write clear and maintainable code, rather than trying to optimize performance prematurely.
eg instead of using a bunch of static to rely on?
when i store it into a variable suddenly it doesn'work
are you still storing it in a variable in the field initializer? or are you doing so in Start like you should be when doing that?
i made the varialbe and then in start
do you assign to the Instance variable in the UIController's Awake or Start method?
start
there you go, that's why. it's Start may not have run before another object's Start
private void Awake()
{
uiController = UIController.instance;
}```
in this test accessing through the static Instance property was faster on average, though had a higher standard deviation meaning it could be slower but isn't necessarily always slower.
Also the test was just calling an empty method on the singleton in a loop 100 times
why when i use it directly it works, but when stored in variable it doesn't
so now you are assigning your uiController variable even earlier than the Instance variable has been assigned to
do this part in Start and assign to the Instance variable in UIController's Awake
what this part?
this
there is just variable and assign
that's pretty interesting result
did you fix that
the order matters
don't spam. and also https://dontasktoask.com/
please i want to create android game
and i am too Noob on coding nothing i know it about coding
please click that link and read it
this is weird now direct reference als crashes
hi give me a moving player script
there are plenty of tutorials for making that yourself, go find one
ask chatgpt
its just a tool
anyone know coding
yes
so help me
but if i might ask developers out here, what best practices are you using to connect classes?
these are my suggestions: https://www.youtube.com/watch?v=Ba7ybBDhrY4
Hey everyone, I'm having an issue on my new project that I didn't have before and I have no idea what is going on. After I configured the joystick in the new Unity Input System, when I have a joystick connected I can't use the keyboard keys anymore, just the joystick ones. If I disconnect the joystick, then the keyboard keys start to work again. Any clue if I'm missing any configuration to enable both?
why my time rapidly decrease, thought i fixed that with coroutines
{
while (true)
{
yield return new WaitForSeconds(1f);
DecreaseTime(1f);
}
}```
you're probably starting a whole bunch of instances of the coroutine, of course you haven't provided enough context to know if that is actually the case or not
this is the function i call ```public void DecreaseTime(float seconds)
{
time -= seconds;
// Update the time text
timeText.text = time.ToString("0.00");
Debug.Log("Time: " + time);
}```
here is where i start it: case GameState.InGame: // Handle the in-game state // Go to the start game scene Debug.Log("Your gamestate is: " + GameManager.State); StartCoroutine(UIController.Instance.DecreaseTimeByOne());
in my game controller sscript
i'm just going to assume you are starting it in Update because you're still not providing enough context
i have nothing in update
I don't recall but is it not possible to use the [field: SerializeField] on List<T> properties?
should be possible
why don't you share all of the code instead of these small snippets that don't give the full context of where/when the code is being executed
Yes it is, I just forgot to add a set to the {get;set;} part of the prop lol, thanks.
UICOntroller: https://hatebin.com/zhkpirkebs
Is there a built in function to invert a layermask?
If not I'll make my own, I'm just curious, and I can't find out if there's a built in function.
Is there a way to schedule an animation? So that it's not frame dependant.
@somber nacelle nvm fixed it.
that's good because you didn't bother sharing where you had started the coroutine yet 😉
you can use ~ to invert a bit/layermask https://unity.huh.how/programming/physics/bitmasks
thx, I just found that
Architecture help
I have a stun mechanic.
I have the MoveToPlayer script.
MoveToPlayer is used both by stunnable entities (such as enemies) and non-stunnable enteties (such as auto-aiming projectiles).
Behavior of the MoveToPlayer changes from stun condition.
Is the best solution is to inherit from MoveToPlayer something like StunnableMoveToPlayer to implement stun logic there? That way all the movement logic will be there and I would be able to override parts that are affected by stun.
either that or you use composition.
add an optional object that can be asked "can the player move" and in that have stun logic
for starters, inheritance is usually fine, just personally not a fan of it because it gets messy to fast
Trying to represent complex objects through a tree of inheritance is the classic recipe for problems.
10 years into your project, you notice that you would like to dock an asteroid to a ship for transportation.
tough luck, asteroids and ships are only 2nd cousins in the inheritance tree
happened to a game i used to mod
I test my code, but I do not test them by writing interfaces because I forgot what they are for. Why should I test my code with an interface?
wdym test with an interface ?
are you talking about the type interface or something else
well interfaces exist if you have multiple classes doing similar things and want to hide that.
easier testing is just a nice side effect
imo its pointless to hide a single class behind an interface, no matter if for testing or not
is useful but , why are you reading java
is it more productive?
wdym more productive, it has it's own usecase
esp if you dont want to use inheritance
it makes swapping out classes a lot easier, so yes it leads to improved productivity in the long run. but you have to figure out a smart interface first which is less productive in the short run
i just searched for oop how to use interfaces so I ended up with whatever language
usually you create the interface if you already have these almost-similar-classes-doing-similar-things
not before you have it
I use them often when i make things like services etc
I would like to use composition, but I can't find the right mechanism.
I don't fully understand what you mean by optional object.
For context, my MoveToPlayer has Update() {move(); }. Do I need some StunnableMovementController, that will call in its update move() if it's not stunned? That way, MoveToPlayer won't be Monobehevior, just a c# class?
MoveToPlayer also has OnCollision logic (to stop trying to move if it's already colliding) and I don't want to duplicate this logic in different MovementControllers.
I don't thins that call OnCollisionEnter { moveModule.OnCollision(); } in MovementController is a good option.
Productivity is relative. Interfaces are ways to "interface" with something. In the context of programming, it's basically a description that says "hey here's how you can use this thing". In the context of testing, you basically start by defining your interfaces so that you can write tests that make sense, and then you write the rest of your code to align with those interfaces so that the tests can do their thing
if you use composition, you dont need a childclass.
you just give your MoveToPlayer a field that takes an object of type "StunManager".
it queries its stun manager if its stunned, but can also handle stunManager being null.
that way its optional to use it
OR you actually use StunnableMovementController which shares an interface with NormalMovementController so the characters can take whatever of the two, without caring which one it is
for example, if I want to be able to ask my book object who its author is, it would be nice if I could just do book.getAuthor(), so I might have a WrittenMaterial interface that says things implementing it need to have a getAuthor method
i'm checking to only decrease time when iam ingame, so for example if i shift to state of game pause this would not decrease, but it is. public IEnumerator DecreaseTimeByOne() { if (GameManager.State == GameState.InGame) { while (true) { yield return new WaitForSeconds(0.01f); DecreaseTime(0.01f); timeText.text = FormatTime(time); } } }
if statement goes inside the while look
otherwise it gets started and starts ignoring the state
You can also define features of a controller class by adding interfaces like IStunnable to it, while querying for them with GetComponent as separate features, if separating into different classes is awkward.
what gamepause, where ?
in my gamecontroller i manage difference states
everything crashed 😭
heh
well you have to handle what the while loop does if the player is not in the game
So i took a look at the profiler to try and figure out where my bidirectional pathfinding algorithm is spending most of its time.
Turns out its when i sort the open lists!
So heres my question. Rather than sorting the entire lists each iteration in the while loop.
How do i implement an insertion sort? whats the best container to do so on given what im trying to achive?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
public IEnumerator DecreaseTimeByOne()
{
while (true)
{
yield return new WaitForSeconds(0.01f);
if (GameManager.State == GameState.InGame) {
DecreaseTime(0.01f);
timeText.text = FormatTime(time);
}
}
}
something like this probably
right, also you dont have an exit condition...
no i use toggle
you can just break the loop on gamepause state
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (GameManager.State == GameState.InGame)
{
GameManager.State = GameState.Paused;
}
else if (GameManager.State == GameState.Paused)
{
GameManager.State = GameState.InGame;
}
}
}```
so basaicallyit would only run when ingame state
while (true)
{
yield return new WaitForSeconds(0.01f);
DecreaseTime(0.01f);
timeText.text = FormatTime(time);
if (GameManager.State == GameState.Paused) break;
}
}```
How can I control an alembic track through code? As in control when it plays.
so getAuthor is the method being tested, and I would have multiple variations of this method to test
Not quite. getAuthor would just be something I could use in a test
You could try swapping to a priority queue
Maybe I have some complex logic that's determining what the author should be presented as, and that may be what I'm testing. getAuthor would just be my window into that world
oh holy smokes! a min-heap!
didnt know that existed in c#
Hoping that fixes your issue :)
Also I think for bidirectional a star you need to keep a lot more lists right? Maybe the overhead is not worth the gain in performance that you get
Might be worth to profile
yea me too.
What namespace is PriorityQueue in? is it not in system.collections.generic? i cant seem to find it.
Oh, In my example I mean that StunnableMovementController is not an child class, just a Monobehaviour.
I don't completely understand how stunManager would inject in the behaviour of MoveToPlayer.
The only way I see, is MoveToPlayer is checks something like StunManager.stunned and changes its behaviour. But that way I will have stun logic in components that don't know anything about stun and don't use it. And there can be more statuses like that, it seems strange to check for all statuses in script that don't actually uses that logic and just moves to player.
The problem with different controllers is that MoveToPlayer have some OnCollision logic that changes state of the component, so I can't
use usual functions from simple c# class there.
meh, not too bothered about memory atm. :>
Not the memory, but you need to sort more lists
well yea, but with priority queue that becomes a non issue no?
by just using the distance as the priority
But not all entities that move, will be Sunnable, so I can't use this interface in general movementController.
then use two different types of MovementController, one for the stunnable type and one for non stunnable.
if you find that they still share to much logic, extract that logic into its onw class
distance + path length I assume?
Also you are right, wouldn't make much of a difference with priority queues
yea, but im unable to make a priority queue x) cant seem to find the correct namespace
Isn't the priority of a path determined by the current path length + the heuristic?
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.priorityqueue-2?view=net-7.0
Oh no
This is since .net 6
wdym?
PriorityQueue datastructure doesn't exist in unity's version of .NET
You can't find the namespace because it doesn't exist
what version is unity using?
oh christ
Since 4.5 ms started working on .NET core 1/2/3, which was later renamed to just .NET
They've still been updating .NET Framework though
The priority queue is .NET 6, so it doesn't exist in the version unity is running
maybe i can just snatch their implementation.
https://referencesource.microsoft.com/#PresentationCore/Shared/MS/Internal/PriorityQueue.cs
Check your .csproj file to be sure
It should be in there
I haven't checked in a hot minute
No, there should be a .csproj in in your project, it details the information about the scripts n stuff, I think one of the properties recorded in it is the .net version
But I could be mistaken
Filename is something like assembly csharp.csproj
It's just an XML file you can open in any text editor (preferably your IDE)
Also, double check your priority calculation
I am pretty sure that just using the distance between the source and target as a priority leads to it being a greedy search
Which will lead to poor performance when there's a lot of obstacles
Hey, so I just wanted some advice, would it be wise to have a debug menu all set up in a different scene so that it can be used either in the scene it’s in directly, or load the scene while in another one and simply load the canvas and pause the game, etc.? Or would it be better if it was all done in script so the script can just be added into a game object in the scene and trigged somehow that way and save space maybe?
when i build my addressables and i'm not using cdn where are they saved ?
So i want to have a delay beetween each animation i make such as if i press "1" it plays animation1 and if he presses button 1 again he has to wait 2 second t o do the attack again> anyone have any idea on how to do this ?
By no means an expert on this but I prefer to just use a prefab and enable/disable it with a key
Loading a scene additively also works though if you have a lot of scenes
float delay = 2;
float timer = 0;
private void Update()
{
if(Input.MouseButtonUp(0) && timer <= 0)
{
DoAnimation();
timer = delay;
}
timer -= Time.deltaTime;
}
something like this
The problem with different controllers is that now MoveToPlayer has its own state that changes from onCollisionEvents.
So with different classes I will need to basically duplicate this state and it's logic.
More abstract solution could be creation of State field of type MovementState. Then, all methods will pass state to MoveToModule (such as move.OnCollision(state). That way all of the base move logic will be handled by this MoveToModule class (just c#, not mb).
Do you think this is the right solution?
i need to get my old schoolbooks out to read up on the greedy search, cant remember.
But you might be right there.
well sounds like collision and stunning should be separate logic objects
also, i really really dont wanna implement my own min heap xD
I linked a stackoverflow post, someone in the comments claimed to have a very efficient Pqueue implementation
aye, ill check it out, thanks
So, regular Dijkstra search just used the current path length to determine the next potential candidate and a* is really just an extension on it by introducing a heuristic (your distance measure in this case) and adding it to the path length
It's not like all collision, MoveToPlayer just use collision to "move while not colliding". And if I extract this logic to my movementControllers, I will need to duplicate it in all controllers.
If you'd only use the distance, it will always pick the node which would result in a lower (probably Euclidian) distance, which is essentially a greedy search
Right, yeah, I was just thinking, since if I were to do scripting, I’d have to pretty much code everything in right? I’m not sure if one would be better over the other, maybe I’m overthinking it though
I feel I might have posted this in the wrong code channel
oh, so im not even using a-star atm. Lmao
Be sure to measure, I'm curious to what degree your solution will speed up!
ill try hah
seems like im failing to implement "f" in the G = F + H calculation 😛
//Sort the queue by distance to the other queues head
if (i % 2 == 0)
{
float f = 0;
KeyValuePair<Tile, Tile> tempCurrent = current;
while (tempCurrent.Value != null)
{
float distance = (tempCurrent.Key.position - tempCurrent.Value.position).magnitude;
f += distance;
visitedFromSourceTile.TryGetValue(current.Value, out Tile parent);
tempCurrent = KeyValuePair.Create(current.Value, parent);
}
queueFromSourceTile.Sort((x, y) => ((x.Key.position - queueFromTargetTile.First().Key.position).magnitude + f).CompareTo((y.Key.position - queueFromTargetTile.First().Key.position).magnitude + f));
}
else
{
float f = 0;
KeyValuePair<Tile, Tile> tempCurrent = current;
while (tempCurrent.Value != null)
{
float distance = (tempCurrent.Key.position - tempCurrent.Value.position).magnitude;
f += distance;
visitedFromTargetTile.TryGetValue(current.Value, out Tile parent);
tempCurrent = KeyValuePair.Create(current.Value, parent);
}
queueFromTargetTile.Sort((x, y) => ((x.Key.position - queueFromSourceTile.First().Key.position).magnitude + f).CompareTo((y.Key.position - queueFromSourceTile.First().Key.position).magnitude + f));
}
Unity crashes 😛
I don't have the time to check right now, can take a look at it tomorrow though, in the meantime someone else could try to help you
Is really no problem, just a little late for me so going to bed in a little bit, let me know if you figured it out or not and I'll take a look if you didn't!
hey anyone know why SetCategoryAndLabel wouldnt work? I have a sprite library and sprite sesolver and renderer. But calling that with a category and label doesn't have any effect at start
Hello! I'm working on an achievement system, but am not sure what I'd need to code to have the game register each scene's collectibles as 'unique' to that scene (specifically so I can have achievements for all coins in a level / all collectibles from all levels, where each level is its own scene). Any help much appreciated!
Item collector script - https://hastebin.com/share/moluxatade.csharp
Datamanager script for saving & loading - https://hastebin.com/share/jexifawiko.csharp
yo squid just have a bool for each scene ? like bool AllCoinsCollectedInScene1
U might have to make a singleton or some sort of static class to implement that but thats my first guess
Is it possible to create type of scriptableobject that implements interface?
Or the only way is to create abstract class ( : SctiptableObject, IMyInterface) and then inherit all classes from it?
🤔 It's an option, I just wonder how I'd tell the DoNotDestroy object thing I have what scene it's currently in
Ahhh i see ur data manager class seems big as is but u might have to add to it
U could mark each coin with a tag for each level Squid
That way u dont really care about what scene ur currently in just what coins belong to which scene
@winged birch
I dont see why you couldnt just give a ScriptableObject an interface and implement it there, or if youd like, maybe make a base ScriptableObject class that has a virtual implementation of the interface that you make others from, the second way probably only makes sense in specific scenarios, but I dont see why either would be a problem
True - I'm thinking of adding a 'using Unity.SceneManagement' to my ItemCollector script and having it read the name of the current scene it's in
It'd be a bit messy but then I could just have if statements for each level telling it which one this collectible belong to
That should work as well both are going to require a bit of spaghetti code but itll get the job done
ha, expect to see me back in a day or two when something gets buried in the spaghetti. thanks for your help
could you use Object.DontDestroyOnLoad on a collectable manager that would grab all the collectables in a scene when it's loaded to track that?
I have some scriptable objects that implement interface.
And i want to create a field in another class that can store these objects.
Not sure if it would work, but you could try giving each coin some int ID, and use that ID in a dictionary of your scenes and list of coins, using a broadcaster/messages/events, you could track which coins were collected by ID, then save/load that dictionary to file as needed, again not completely sure if this approach would work, just one that comes to mind
my tag idea ^^
I think giving the coins some sort of id is the best route personally
yea
if you need every coin to have a unique ID that you don't assign in the inspector that's persistent you could store it in a file
Mm, I've not dabbled in dictionaries but could give it a go
Not really each specific coin more so coins in a specific scene
I believe thats what he wanted i shouldnt speak for him
if its each specific coin thats a different can of worms
Could you not cast the interface? Something like this maybe:
public class SomeSO : Scriptable, IInterface
{
public void IInterface.SomethingSpecific() {}
}
public class SomeClass : Mono
{
public SomeSO so;
var thing = (IInterface)so;
thing.SomethingSpecific();
}
I dont think i understand his question
Just make a reference to the S0's
Do interfaces prevent them from being referenced ?
Nah, its just that SO's are not componets or part of the scene, so you cant use something like GetComponent or anything you would from a GameObject normally, but I may also not fully understand the context of their goals, just making a suggestion
OOOOHHH
he cant call the interfaces functions
because theres no GetComponent
i getcha
I need something like this
public class SomeSO1 : ScriptableObject, IInterface {}
public class SomeSO2 : ScriptableObject, IInterface {}
public class SomeSO3 : ScriptableObject, IInterface {}
public class SomeClass: Mono {
public <someType?> SomeSO; // can store SomeSO1, SomeSO2 or any ScriptableObkect that implements IInterface
}
List<>
Thats what i thought u meant honestly U just want a container for the SO's right ?
I'm not 100% sure how I want it to work at the minute, so this might be a bit confusing, but bear with me - this is the idea
- Each level has 10 silver coins, 5 gold coins, and 1 red / blue / green gem
- Their collection is sort-of tracked through this script - https://hastebin.com/share/moluxatade.csharp
- I'm working on achievements that persist between scenes, from 'collect all silver coins in level 1' to 'collect all gold coins in the entire game'
- When the player dies / restarts a level, all coins and gems are 'uncollected', which may cause issues?
- Achievements, when unlocked, should never be re-locked
- player data is saved via a DoNotDestroy object that has this script - https://hastebin.com/share/jexifawiko.csharp
the solutions y'all were offering should still be valid, I'll give dictionaries a go, but hopefully that clarifies a bit
it does reset the scene on player death, though, which makes me worry
Partially to be annoying -- this is for my dissertation on achievements affecting player engagement, so it's to see how badly players want 'em (if they'll keep going for all coins after dying and losing their progress in that level)
I can look into just a proper respawn mechanic if that's at odds with reality though
Ohh yeah, Vee has a good point, you could make a List<ScriptableObject> and assign SO1,2,3 in it, and if you know they all have that interface, you can then try the cast on some index of the list, or create a base type that uses the interface and make each inherit from that, for example:
public class SomeSO : Scriptable, IInterface {}
public class SomethingSpecific : SomeSO {}
public class AnotherSpecific : SomeSO {}
public class SomeClass : Mono
{
public List<SomeSO> ...
}
Squid homie ur overthinking it lol
Just make a method that handles the player death OnDeath() { coins = 0 )
Yeah, for SO's that implement exact interface
🫡 I'll do some tinkering and report back. thank you gamer
Ok so my first thought was...and this a shitty thought mind u
Just make SO's that implement that interface and make SO's that dont
And if those SO's are on a gameobject check the gameobjects and not the SO's
But I want to this variable to has this interface methods, that so's implement
SO's cannot be attached to game objects, they can be referenced on scripts, that use MonoBehaviour to be attached to a game object though
the scripts i meant sorry dibbie
Yeah, I thought about base class with inherited so's
Thanks, I'll try it
If you want to access them directly, you could extend that example with virtual functions, for example:
public interface IInterface
{
public void Something();
}
public class SomeSO : ScriptableObject, IInterface
{
public virtual void IInterface.Something() {}
}
public class SomethingSpecific : SomeSO
{
public override void Something() {Debug.Log("do something cool");}
}
Then you should be able to call it with something like
public class SomeClass : Mono
{
public List<SomeSO> data
data[someIndex].Something();
}
If someIndex happens to be 2, and your list of data happens to be 3 or more elements, and in this example, lets say index 2 of your data happens to be SomethingSpecific, then that class can decide what "something" interface does, in this case, log to the console
This is my sign to learn about virtual functions
arent they just methods that overwrite the parents definition of the base method or am i mistaken?
I think I'll use this approach, thanks for the help :)
It can be useful for inheritance, like if you have a base "Weapon" class that uses a virtual "Attack", a bow and a sword could override that, in Unity you might find yourself with a lot of those "modification of existing thing", but if you want a hybrid weapon tthat is both a bow AND a sword, then inheritance may not work well - or you can but youll end up with 3 or 4 classes to make the hybrid work
Hi, I'm trying to learn how to convert my hand movement in local space so that it results in the same movement around a robot. Right now I'm just getting the difference in hand position between each frame and scaling it then applying it to the robot target but that could move it in a bunch of directions not based on where I'm looking. Any ideas?
This is C#, not OPP. Each language implements abstraction differently.
OPP is a paradigm.
its OOP*
i was trying to say that an absract classes abstract methods sound the same as virtual methods
sorry if that wasnt clear i was just trying to get a better understanding i prolly just worded it badly my apoligies
and c# is very much OOP
Maybe not as much as python and javascript
The one benefit of a virtual method is its entirely optional to implement - an abstract class (at least in C#) is required to implement, and (I could be wrong) I think it also has to be a part of a abstract class, where a virtual function can be a part of any type of class
C# is way more OPP than python or javascript.
They are not even compiled nor typed. You need to go out of your way to make OPP with Python or Javscript.
its O O P i dont mean to pick on u i promise
Object Oriented Programming ?
ur writing OPP
You are not... OOP is a paradigm that you follow.
There is Data Oriented Programming
Procedural
Functionnal
Ok so whats opp
A paradigm
whats the acronym
lets move on
Im working on an app where the user takes a photo or selects a previous photo and text is extracted from the image. I am hung up on how to extract the text from the image
You probably want (need) some ai for that
i was hoping to use some form of opencv or something
There are pretrained text ocr models
ok, how can i implement them
the good ones you don't implement, you'd use the cloud API they provide, simpler ones like tesseract are just a google search away, their gitlab readme should give you all the info you need https://github.com/charlesw/tesseract
most of the simple ones are nowhere near as capable as recent AI hype would make you expect
isnt tesseract python only?
I couldnt find tesseract for untiy
its a c library with bindings in many languages
the repo i linked is the c# variation
if i used this charlesw/tesseract could i have ads in my app or would i need to license it
you need to research that, tesseract itself is apache-2 https://github.com/tesseract-ocr/tesseract/blob/main/LICENSE
apache 2 confuses me
it says commercial is allowed but then it says something about a notice
you generally have to include a notice about which libraries you use in any software you make that uses them
only stuff like MIT license is really transparent to the end-user
So just a little "this app uses tesseract" thing at startup?
usually you'd have a button somewhere that shows a list of them all
interesting, thanks!
Why am i getting this error?
public class PathFinder
{
public List<Node> QueueFromSourceTile { get; private set; } = new List<Node>(new NodeComparer());
public class Node
{
public Node(float _f, float _h, Node _parent)
{
f = _f;
h = _h;
g = f + h;
parent = _parent;
}
public float g { get; private set; }
public float f;
public float h;
public Tile tile;
public Node parent;
}
class NodeComparer : IComparer<Node>
{
public int Compare(Node x, Node y)
{
return x.g.CompareTo(y.g);
}
}
}
i have to cast explicitly like so new NodeComparer() as IEnumerable<Node>.
How do i get around that? 😮
Because what you're trying to do doesn't make sense..? I don't think list constructor can take that as an argument.
Wdym? What are you even trying to do?
Then use a sort on your queue or something. You're just trying to assign an empty list with a weird parameter.
public SortedSet<Node> QueueFromSourceTile { get; private set; } = new SortedSet<Node>(new NodeComparer());
this worked
what i really want is a priority queue, but as someone else pointed out earlier, they're not implemented in the version of .net that unity uses
Wanted to ask about modular AI movement system.
I have behaviour where enemy moves towards the player.
I also have behaviour where enemy moves towards the player only to some distance, and then maintain this distance.
Also behaviour where enemy dashes on some condition.
I want flexible way to compose AI movement. For example, I want to create some way to create variations like [towardsPlayer + Dash] enemy, [towardsPlayer + maintainDistance + Dash] enemy, [maintainDistance + Dash].
My first Idea was to create movement decorators with ScriptableObjects, but there is some problems with this approach. For example, towardsPlayer triggers on collisions to check if its "arrived", so if I want to wrap it, I will need to redefine onCollision triggers in the whole wrap link.
Also I have some problems with passing dependencies. Components such as rigidBody and enemyTransform should be public to define them in Start() of movementController which doesn't seem right way to do.
Is there are ways to solve this problem, or maybe different approach?
Hello, I'm not sure if this is a more begginer problem and I'm just stupid but can someone please tell me why this code doesnt work
if(PlayerCam.rotation.y > 0f && < 90f) {
}
because rotation is a quaternion
and rotation.y is not at all what you think it is
.eulerAngles, .localEulerAngles depending on the space you want
so I would use .eulerAngles.y ?
yes
i got the same error
may be the && < 90 needs
you should do (a > 0 && a < 90), not (a > 0 && < 90)
this was the error
i'll try that
IT WORKS
So, I'm making a game over scene with a couple of buttons. I also have a script attached to a game object to contain the button functions, which I then attach to the buttons in the editor. But when I look for the methods that each button should use, I can't actually select a method from the script.
I tried doing that first and it didn't work, which tells me I even screwed that up somehow cause it worked just fine when I tried it this time.
No clue. But thanks!
Hey guys, my intellisense for Unity just blew out for VSCode and it hasn't come back for 2 days so I've been relying on Unity's error log...I have Ryder but idk how to use it yet as well as vscode--would Ryder be a better option?
So I am developing a 2d top down roguelike, obviously it has procedural dungeon generation. I made a mini map that displays the dungeon and your current room witch works perfectly as I intended. However my problem is because I didn't use a Canvas and instead used world space game objects with sprite renderers on them, the mini map appears on different position across different screen sizes. I was wondering if there is a solution to this where the map will always appear in the top right of your screen, or if I have to completely rewrite my code to use a canvas instead of a game object. Thanks
Rider is way better than all the other options
aight i'm going in
would that apply for every programming language? idk how many languages it supports
there is a similar quality IDE from the same company for all relevant languages
ooh what's that one called?
anyone know why array[^0] (to access from end) might not be working?
throwing outside range error
im sure the array is not empty
it's an array of non-value type calsses
it's kind of maddening TT
the caret makes the code so pretty
array.Length - 1 will have to suffice
It's ^1 for the last index
I've never heard of that syntax at all.
It's new . . .
Is it a unity or a c sharp thing
oh dang, thanks!
C#, introduced in c# 8, but you can use it in unity 2021+
https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/ranges-indexes
how do i change the size of camera in c#
How to do a suspension system for a car using Unity's builtin components?
I'm using spring joint, but the tire seems to be disconnected from the attached rigidbody and thus is getting dragged by the vehicle.
I want the suspension to act like a shock absorber. So it smoothens out any bumps and potholes and doesn't just move with the terrain.
where can I put meta data inside of Unity Gaming Services (eg base stats for enemy/characters)
Im not sure if im in the correct channel asking this. But im trying to make a BFS compute shader.
However im a complete novice when it comes to HLSL.
https://pastebin.com/6mf2tagK
Im getting error upon error from the Unity compiler. I dont understand what i am doing i think...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what error is that?
Some things I found are:
- You don't change queueSize in the methods you
inoutit. - You don't actually use
id.. this makes it single threaded, and even worse, does the operation in each of the 64 threads that are assigned as workers.. which is worst-case-scenario for compute shaders. - You just output an int. That's not useful at all from the CPU.
Notes:
- That's not a good way to use a compute shader.
- You'd ideally want to make it multi-threaded and output something the C# part can use (e.g.: path to node).
- It would help if you thought of Compute Shaders as modules that do certain stuff and return nice outputs for you to use in C# or Screen directly.
Implementing Bi-Directional A* in C#
Anyone else have issues with Unity 2022.2.12-13 making your C# files read-only, so you cant save in Visual Studio ? I have to force a domain reload to fix the issue. Its happening constantly
which is faster, GameObject.Find or GameObject.FindWithTag?
well I assume the second one is faster, but idk
They're both slow. Use whatever fits your bill.
The first relative to name. The second relative to tag.
both shouldnt be used
its not just slow, its also unsafe.
if you use "find" it means you have no idea how many of these objects actually exist.
leading to all kind of edge cases. "exactly one found", "none found", "Multiple found" etc
this doesn't answer my question
I know they're slow
void Moving()
{
Vector3 movement = p_input.xAxis * transform.right + p_input.zAxis * transform.forward;
movement *= speed;
movement += new Vector3(0, rb.velocity.y, 0);
rb.velocity = movement;
}```
Hi sorry, i managed to create movement but how do i rotate with this input? 😅
hello all... how can i check if 2 fields are equal??
I would like to ensure that when the user chooses a password he must also confirm it ... in this case I make the button interactive
I tried like this but I can't also because thinking about it, the 2 variables for the password are always emptyif I don't confirm them first...
if (confirmPassword == password)
{
ConfirmRegButton.interactable = true;
ConfirmRegButton.onClick.AddListener(() =>
{
StartCoroutine(Main.Instance.Web.RegisterUser(UsernameRegInput.text, PasswordRegInput.text));
});
}
how would you create a reference to a GameObject in a static class?
other than using Find
Both do string comparisons. The answer is that neither would be significantly faster than the other.
doesn't Find scroll through whole scene, while FindWithTag only scrolls through specific tag?
not sure if that is true
Only with https://docs.unity3d.com/ScriptReference/Transform.Find.html would you narrow it down to child objects of a transform.
I imagine Unity would keep track of objects with a tag in a dictionary or something for faster lookup
actually it's quite the opposite. if you have an idea that you have one object of specific tag or name, they are absolutely usable
They might as well do that with names as well right?
sure, but not all objects will have tags
Pretty certain tag is explicitly in the inspector for every game object.
yeah, but it is optional
in general yeah, avoid any Find function
you could have your own manager to store specific objects under certain conditions too
or use static lists (though i'd avoid that, more hassle if you turn off domain reload)
I'm not on a workstation but I believe all game objects have tags. Ideally untagged objects should be tagged "Untagged".
either way, i still think FindWithTag is going to be quicker than Find
i would have the object set itself as a reference to the static class, and through load order make sure object loads before the class
Can someone please tell me where I can find the Dynamic Batching settings in URP ?
URP doesn't really use dynamic batching
If I have 60 moving cubes in scene with same material and SRP batching compatible can I get less than 60 batches with URP ?
"Batches" don't really matter to SRP batching afaik
It doesn't reduce batches but it reduces the cost of them
Then Im stuck with one batch for each cube ?
"Stuck"?
The code din question also does not contain the problem you are having
I mean isnt there any way to decrease the draw calls ?
*stuck with a draw call per cube
this is more like a code design question
im currently using new input system, on player script i have all the events i needed, but i want to pack them well so my player script is less messy
public void OnReload(InputAction.CallbackContext context)
{
if (context.performed)
{
gunConfig.StartReload();
}
}```
something like this
now i have a total of 8 actions
i have 3 scripts, movement, player and shoot
do i leave these events on player, or move them away to those scripts?
Do you need to? SRP batching makes them cheap anyway
You could disable SRP batching and use static batching or GPU instancing, but those often perform worse with more effort than SRP batching
im quite braindead now lol
Do you think SRP batching with 150 drawcalls will run well on weak mobile devices ?
I have no experience with mobile development and the performance gains depend on how you scene is set up, but I guess it might
The best way to test it is to make a build of scenes with a "typical" setup of geometry and effects, each using a different batching method
Where can I disable SRP batching ?
Hi,how do i make a bubbly oil liquid in unity
You could have another script just for reading input events and passing the signals to other scripts
I think some Unity's examples like Starter Assets do that
Thanks
What kind of liquid do you mean? This is the coding channel so I assume you don't mean visuals
oh no i mean the visual like boiling oil visual
Also, If I change the property of a material referenced in inspector has any differences than changing the properties through sharedMaterial ?
There isn't really a one way to make something like that so you'd google for references and examples of how others have made similar effects, google for bubbling oil tutorial, if you find none such then you'd google for bubbling tutorial, oil tutorial and liquid tutorial and try to combine them
You'll probably need to make textures, shaders and particle effects
i did alot of research ive already done the particles i just need a oil type material without any physics
If you change it 'in inspector', then I think no difference
If you change a material in code that's 'referenced in inspector' then it would create a material instance
If you think about it oil is just dark, opaque water with an iridescent surface
So that's two smaller concepts you might find resources for more easily
Can you SerializeField a class type?
For example, if I have a class names weapon with a few variables, and I type: [SerializeField] Weapon Axe;
Why don't the variables show in inspector?
Weapon needs [Serializable]
And dont put it on the field but on the type declaration
Ooh thanks!
"The type or name space "SerializableAttribute" could not be found"..?
ask your IDE to fix the error
How?
the attribute should be red underlined and you can right click it
Okay I figured out the issue. Apparently I needed to say "[System.Serializable]", not just serializable
yep, because Serializable is in the System namespace
your IDE will hunt those down for you
but it's useful to understand what's going on
hey guys, ist this:
void Start()
{
healthStat = new Stat(healthDefinition)
}
and this:
void Start()
{
AddStat(healthStat, healthDefinition)
}
void AddStat(Stat _stat, StatDefinition _statDefinition)
{
_stat = new Stat(_statDefinition);
}
not doing the same thing?
I want to make a copy of the stat and save it to a List later on, thats why I want to make a function for that.
First method works fine, second doesnt..
is Stat a class or struct?
a class
yeah, don't think you can just send a variable and reassign like that to the parameter
Consider out Stat stat and out healthStat
or just use
Stat AddStat(StatDefinition _statDefinition)
{
return new Stat(_statDefinition);
}
oh that works perfectly, thank you guys!
Okay I need help, I'm currently building a script that checks of all of the items in a Drag and Drop system is placed in the correct order or not. If they are it should play the correct sound effect, if it's wrong it should play the wrong sound effect. First I check if all the DropItems are filled, then I check if they are in the correct order: IsIDListInTheCorrctOrder(GetInFilledDragItemsID()) and from that play either correct or wrong audio. So the issue is that since it runs every frame, when its true or false, it keeps running, but I only want it to run once when the value change. How do I do this?
Here is the code:
void Update()
{
if (IsAllDropItemsFilled() == true)
{
if (IsIDListInTheCorrctOrder(GetInFilledDragItemsID()))
{
CorrectAwnser();
}
else
{
WrongAwnser();
}
}
}
You can keep an extra boolean -> set it the first time the condition is true, and then check if its not true in the win condition itself
you could trigger some kind of ListChanged event (and/or ListItemAdded/Removed/Ordered/etc) and only check then
ahh, that a great idea, thanks
I'll try it
Works wonderful, I've been stuck on this for a while, don't why I didn't think about this before, thank you SO much : )
Does anyone know how I can stop my character from getting stuck on walls? I tried a frictionless rigidbody but that just makes it possible to run up impossible angles.
Detect the ground angle (usually with the normal from your RaycastHit or Collision) and rotate your movement direction with that ground angle
This is so you can run up slopes
can someone help me figure out how this works? a animation event with customevent (string). this is from an asset so I'm not sure what it's doing (in a different context, this would normally call the "Hit" method on any? or every? script that the animator is also attached to. I just dont know what it's doing here)
nvm, I found it. I thought it was a generic unity feature but it's not
Guys I’m trying to write a custom cutscene handler where there’s a typedef( or whatever you call it in c#) and a list of those typedefs, and there’s a timer, and I need to read the contents of the variables in the list to get the time that the cutscene happens
But idk how
Or better yet, the question is just:
How do I read variables from a list then check when a specific requirement is met with those variables
Hello, my goal is to build a generic entity spawning system based on triggering an event when an entity despawns that would call a handler defined in the spawner game object. I wrote the following interface:
public interface IDespawn : IEventSystemHandler
{
delegate void EntityDespawnDelegate(IDespawn despawn);
event EntityDespawnDelegate entityDespawnEvent;
}
The idea is that a spawnable entity implements that interface. Here is my attempt at implementing the interface:
public class DummySpawnableEntity : MonoBehaviour, IDespawn
{
public delegate void EntityDespawnDelegate(IDespawn despawn);
public event EntityDespawnDelegate entityDespawnEvent;
void Update()
{
if (Input.GetKeyDown("space"))
{
if(entityDespawnEvent != null){
entityDespawnEvent() ;
}
}
}
}
That won't work, the issue being:
Assets/Scripts/DummySpawnableEntity.cs(5,52): error CS0738: 'DummySpawnableEntity' does not implement interface member 'IDespawn.entityDespawnEvent'. 'DummySpawnableEntity.entityDespawnEvent' cannot implement 'IDespawn.entityDespawnEvent' because it does not have the matching return type of 'IDespawn.EntityDespawnDelegate'.
Implementing entityDespawnEvent does not make any sense right? What exactly is the return type of EntityDespawnDelegate?
Since I can't find any other similar approach on the internet, I take it it isn't a very good one.
Hi there fellas i need to calculate the uvs for a quad. The texture the quad is using is a atlas of all of the tiles. I need to define a area when it calculates the uv with a index. The code bellow doesn't take this "area" in consideration. I need the parameter to be like this: IndexToUVs(int i, int topLeftCornerOfTheAreaInPixelsX, int topLeftCornerOfTheAreaInPixelsY, int areaSizePixelsX, areaSizePixelsY). Thank you for reading!
public Vector2[] IndexToUVs(int i) {
Vector2[] uvs = new Vector2[4];
int atlasColumns = tileAtlas.width / (int)tileSize.x;
float atlasWidth = tileAtlas.width;
float atlasHeight = tileAtlas.height;
float u = (i % atlasColumns) * tileSize.x / atlasWidth;
float v = 1f - ((i / atlasColumns) * tileSize.y / atlasHeight) - tileSize.y / atlasHeight;
uvs[0] = new Vector2(u, v);
uvs[1] = new Vector2(u + tileSize.x / atlasWidth, v);
uvs[2] = new Vector2(u, v + tileSize.y / atlasHeight);
uvs[3] = new Vector2(u + tileSize.x / atlasWidth, v + tileSize.y / atlasHeight);
return uvs;
}
Because it's not public
Hi everyone. Im trying to change the opacity of a group of images in an "animated" way, but I get error NullReferenceException: Object reference not set to an instance of an object Spawner.Update
My code:
public class Spawner : MonoBehaviour
{
Image[] imagenAdvSpawn;
Color color;
float opacidad = 0;
bool corrio = false;
GameObject[] objetoImagenAdvSpawn;
void Start()
{
color = GameObject.Find("Imagen Adv Sp").GetComponent<Image>().color;
objetoImagenAdvSpawn = GameObject.FindGameObjectsWithTag("ImagenAdv Spawn");
imagenAdvSpawn = new Image[objetoImagenAdvSpawn.Length];
for ( int i = 0; i < objetoImagenAdvSpawn.Length; ++i )
{
imagenAdvSpawn[i] = objetoImagenAdvSpawn[i].GetComponent<Image>();
}
}
void Update()
{
if(!corrio)
{
StartCoroutine(CambiarOpacidadImagenAdvSp(0f, 1f, 2f));
}
color.a = opacidad;
for (int i = 0; i < imagenAdvSpawn.Length; ++i)
{
imagenAdvSpawn[i].color = color;
}
if(Input.GetKeyDown(KeyCode.T))
{
Debug.Log(objetoImagenAdvSpawn.Length);
}
}
IEnumerator CambiarOpacidadImagenAdvSp(float opacidadIncilial, float opacidadObjetivo, float duracion)
{
corrio = true;
float timeElapsed = 0f;
while(timeElapsed < duracion)
{
opacidad = Mathf.Lerp(opacidadIncilial, opacidadObjetivo, timeElapsed / duracion);
timeElapsed += Time.deltaTime;
yield return null;
}
opacidad = 0.5f;
}
}```
which line is erroring in the update?
Can y’all help I’m using unity recoder to get a video from a camera to a video file how do I set the camera it is set to? I’m using the movie sample
https://i.imgur.com/sVgdHwe.png
How would I access the TMP_Text of TextMeshPro inside my Stone.cs Script? I have over 50 Stone GameObjects, would I need to add the Score.cs Script to every single one of them or is there an easier way?
Anyone know what this warning means?
presumably you only want 1 score script which is controlling the text?
Yes, but I don't understand how I could access it in every single Stone script
make it a singleton
so you can access the static instance anywhere in code
do you know what that means?
I don't know but it says cs:32, which is the line after the color.a = opacidad
yeah I have used singleton before but need to look it up.
Thanks
imagenAdvSpawn is null.
huh, but it should be set in Start
you 100% sure line 32 is for (int i = 0; i < imagenAdvSpawn.Length; ++i)
screenshot the error
the line is this : for (int i = 0; i < imagenAdvSpawn.Length; ++i)
i just notices i write "imagenadv spawn" instead of "imagen adv spawn"
thanks for the help my brain stopped working such a stupid mistake
I am trying to get a network variable to be static, but it keeps giving me an error saying NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?
Does anyone know why this is happening
Netcode for Gameobjects?
Yes
Sorry I should have said that
I am making a tag game and I am storing a static variable on who the tagger is
And thats the error
tbh i'd be surprised if you could make a NetworkVariable static
Do you know how I should do it then?
i donno, have a networked manager and store it there
Looking for helpful devs for my new project
It doesn't work at all now
It just gives me the error
the same error?
Yeah
.... you've moved it to a manager
Yup
don't make it static anymore
And even when it was not there and not static it gave the error
its not static anymore
try reloading Unity
It asks if I am modifying the variable before its spawned
can some one help me with something https://hastebin.com/share/oxitapiget.java my if statement under declare war don't work and I asked chatgpt 15 times and all his answers were the same useless
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Also I reloaded
that is not C#...
yea i know but i dont know were else to ask
I'm sure theres a Java discord somewhere
i sure dont know any
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I have a monobehaviour that interpolates it's position to a 'next position' every frame. When i move this monobehaviour in the editor, i need the 'Next Position' to change, instead of the transform position. Is there a way to override the behaviour of moving a game object in the editor
do unity compute shaders not support a byte type?
ah, so no
One message removed from a suspended account.
One message removed from a suspended account.
My VR game is freezing every 4 seconds. I am running standalone on the meta quest 2 using the Oculus XR plugin. I have tried opening the profiler and checking what was taking so many frames. The first thing was the EditorLoop, but I don't think that has anything to do with the game itself as I am sending the built apk to the headset.
I read somewhere that 3rd party plugins may freeze the program so I tried removing a couple. The most significant change happened when I tried removing the oculus XR plugin. This gave me much better fps, but obviously it stopped launching in VR.
None of my scripts seem to take much power and I have no idea what I should be looking for at this point. Any idea as to what might be causing this?
how do u guys apply recoil force on the character?
just like when u keep shooting, the character will keep looking upper and upper
my method is more like a bandaid cuz i really cant think of a better one
cinemachine noise
dayummmmmmm
do u know how i did it?
private IEnumerator ApplyRecoil()
{
yield return new WaitForSeconds(gunConfig.recoilWindow);
recoilX = 0;
recoilY = 0;
}```
i basically hard code out the cinemachine noise
I mean it's a way of many ways to do it sure
//implement recoil
if (IsAiming)
{
camConfig.recoilCamMove(recoilX * aimCompensation, recoilY * aimCompensation);
}
else
{
camConfig.recoilCamMove(recoilX, recoilY);
}```
where camConfig is the camera control script on a cinemachine
Ok, so I wanted to get some more opinions, for a debug menu, would it be wise to make it visually and then keep it in one separate scene and while in another scene, load it asynchronously and use it that way, or create the debug menu entirely in scripting like spawn in the canvas, buttons, their positions, etc. and make a gameObject, apply script to it and make it a prefab? I guess I was thinking of making two, one in a separate scene, and one during actual gameplay
it doesn't matter magix you can create it and spawn it from a prefab or load a scene with it additively or do it in code it really doesn't matter
My VR game is freezing every 4 seconds. I am running standalone on the meta quest 2 using the Oculus XR plugin. I have tried opening the profiler and checking what was taking so many frames. The first thing was the EditorLoop, but I don't think that has anything to do with the game itself as I am sending the built apk to the headset.
I read somewhere that 3rd party plugins may freeze the program so I tried removing a couple. The most significant change happened when I tried removing the oculus XR plugin. This gave me much better fps, but obviously it stopped launching in VR.
None of my scripts seem to take much power and I have no idea what I should be looking for at this point. Any idea as to what might be causing this? (Repost because I really need help)
So i have this issue where i made the main menu play button and it just doesn't work,it's like it's not detecting my mouse
mmmm.... Delegates
anyone knows why github dont always recognize changes in scriptable objects? if i have a bool in a scriptable object and check it, the changes in github dont update
Bro who tf made it so raycasts collide with the casting object it is the most stupid bs ever
raycasts are not owned/cast by any object, they are static queries into the physics world
Well surely the stack trace gets which script created the raycast, it cant be too hard to just say "Hey ignore a hit if the object contains the script that created the raycast" (Unless it is)
If you start the cast from outside the bounds of your collider, it shouldnt be detected, or you could put the casting object on a layer the cast isnt checking if your using a layermask to detect, or cast to all, cache the returned array and use something like Linq to filter out the casting object, but there may be a small performance cost to the latter approach
yeah, Ik its easy to workaround, but its still a little annoying
The physics settings have options for that...
oh lol, yeah I need to look at settings more
Is it possible to make an emmisive material light up its surroundings?
Can someone help with mp4 creation I wanna know how to pick a specific camera with unity recoder
Hi, has anyone experienced this error when trying to Build?
An asset is marked with HideFlags.DontSave but is included in the build
ok, super simple question.
class SomeClass {
int i;
}
class SomeClassUser {
SomeClass someClass = new SomeClass();
public void ChangeSomeClass()
{
someClass = null;
}
}
If i call on ChangeSomeClass() on my SomeClassUser object.
Does the old SomeClass get destroyed ? or do i need to deallocate it manually in C# ?
it will be clean up by the garbace collector on its next pass if it's out of scope / has nothing referencing it
fair enough, garbage collector does a lot of the work for us in C#.
You could simply test it with a destructor (finalizers in c#) https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers
Any idea what I'm doing wrong here?
Configure your ide and lookup the docs. Else it says that type doesn't have a definition for what you're attempting. The docs for SplineContainer https://docs.unity.cn/Packages/com.unity.splines@2.0/api/UnityEngine.Splines.SplineContainer.html
IDE is configured, they just need the correct object
(that function doesn't exist in the docs, so I'm not sure where they're getting the idea it exists from)
So why not use SplineUtility?
I wasn't sure. Some minor stuff were missing (reference count etc) and ide should have suggested that it wasn't valid - unless they ignored it and just simply had us try to fill in the gap.
If errors are underlined, the IDE is configured
Sorry I'm just very new to coding and never worked with Splines in unity, I'm really lost on what to do
I have a gun system which works by firing rounds of bullets at a time. Like there is a gun which fires 4 bullets per round, and a total of 5 rounds per reload. I am using coroutines for this. There is fire bullets coroutine which is responsible for actually firing the individual bullets, and then there is a round coroutine which is responsible to start rounds in case the primary fire is held down. Like if you hold the primary fire, I want the fire_rounds coroutine to start, which starts fire_bullet coroutine.
Code looks like this :
public void CalledWhenPrimaryFireIsPressedDown(InputAction.CallbackContext context){
if (context.action.phase == InputActionPhase.Started)
{
Debug.Log("<color=green>Firing Rounds</color>");
fireRoundsCoroutine = StartCoroutine(FireRounds());
}
else if (context.action.phase == InputActionPhase.Canceled)
{
Debug.Log("<color=red>Stopping Fire</color>");
if (fireRoundsCoroutine != null){
StopCoroutine(fireRoundsCoroutine);
fireRoundsCoroutine = null;
}
else Debug.Log("Fire Rounds Coroutine is Null");
}
}
private IEnumerator<WaitForSecondsRealtime> FireRounds()
{
int roundsFired = 0;
while (roundsFired < maximumNumberOfRounds)
{
Debug.Log("<color=yellow>Round Started</color>");
StartCoroutine(FireBullets());
yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime;
roundsFired++;
}
}
private IEnumerator<WaitForSecondsRealtime> FireBullets()
{
int numberOfBulletsFired = 0;
while (numberOfBulletsFired < numberOfFiresPerRound)
{
Debug.Log("Bullet Fired");
yield return timeBetweenFiresWaiter;
numberOfBulletsFired++;
}
}
This works, a little... Like when I press the primary fire for the first time, it works perfectly, but when i press it again, a strange pattern appears.
It looks like two coroutines are starting at the same time
that makes more sense, thank you!
configured for 4 bullets per round and 5 rounds per reload
I feel like I am not ending coroutines the correct way, when primary fire button is released.
Where does "Round Started" get print?
Ah, I see.. cs Debug.Log("<color=yellow>Round Started</color>");
whoops updated the code, there was this another function but i removed it cz discord wont allow long msgs
I missed it initially mbmb
So are you wanting more than one instance of the coroutine "FireBullets" to operate?
If not, simply do not allow the starting of that coroutine till it's done.
I just want the same pattern to continue, like if you see before the first Stopping Fire, Rounds start, and fire bullets. Once each round completes, another one starts, until the max number of rounds are done.
For some reason, when i press primary fire again, two rounds start at the same time
idk why is that happening
Break that thought down. Do you want more than one instance of the FireBullets coroutine?
At any time, one FireBullets coroutine should be active.
Which will be firing bullets at that time. Once that coroutine ends, another one starts because FireRounds is starting another one.
One thing is that, FireBullets always completes before another one is called
What if it's started again before finishing?
What if there was a delay?
And timeBetweenRoundsWaiter was true. So a new round would have started.
I have time values adjusted so that it never happens. Time between bullets is like 0.1, time between rounds is 1 sec
there are 4 bullets per round
0.4 sec in total for FireBullets to end
after 0.6s another one is started
timeBetweenRoundsWaiter is cached WaitForSecondsRealtime
timeBetweenFiresWaiter = new WaitForSecondsRealtime(timeBetweenFires);
timeBetweenRoundsWaiter = new WaitForSecondsRealtime(timeBetweenRounds);``` so it cant be true
Sounds iffy. Maybe avoid firing bullets again until you've finished firing: ```cs
private Coroutine firingBullets;
private IEnumerator<WaitForSecondsRealtime> FireRounds()
{
int roundsFired = 0;
firingBullets = null;
var stillFiringBullets = new WaitUntil(() => firingBullets == null);
while (roundsFired < maximumNumberOfRounds)
{
Debug.Log("<color=yellow>Round Started</color>");
firingBullets = StartCoroutine(FireBullets());
yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime - Minimum wait time
yield return stillFiringBullets;//Wait till done firing
roundsFired++;
}
}
private IEnumerator<WaitForSecondsRealtime> FireBullets()
{
int numberOfBulletsFired = 0;
while (numberOfBulletsFired < numberOfFiresPerRound)
{
Debug.Log("Bullet Fired");
yield return timeBetweenFiresWaiter;
numberOfBulletsFired++;
}
firingBullets = null;
}```
Can anybody help me? It says I'm missing a ; at (18, 26) but I don't know where that is in my code. Here is the link. https://paste.ofcode.org/YVuSMDKWThNcckzkTbMSPa
Why is this IEnumerator<WaitForSecondsRealtime>? Does that work? Usually coroutines are not declared in a generic manner, and it's just IEnumerator
It does work the first time
well, I would remove that so it's declared normally
Assignment operation
What is that?
var a = new ...
If your IDE is not underlining errors in red and giving you proper autocomplete you need to configure it
Why am I getting this error?
From the line ChunkData.SpawnStuff(ChunkData.Structs[0]);
I get an out of index exception, despite the fact that 0 is in the index.
Likely there aren't any elements available at that time.
If you want proof beyond doubt, log the size. It should correlate with the error. Question would be, why was it of size zero.
Show your implementation of the size check.
Still, this would start the next round immediately after one is completed. Each round starts after a fixed amount of time, say 1 sec. But each round doesn't take 1 sec. One round take around 0.4s
It's your original code with simply an extra handler for "not done firing".
The yield time delay would be identical to what you originally had - plus maybe one frame for the done firing check.
yeah, but my original code is starting two rounds at the same time, thats the issue
You could not with the insertion that I've made. Your original would start two if there were delays.
There wasn't anything catching the possibility of a round finishing earlier than expected.
yeah, two rounds can't be started with your edit, thats true, but it will start it immediately after the other then
Can you show more code please.
Single lines don't have much meaning.
I'm assuming you're checking at the very last minute before the error fires.
If so, it would be zero as that's what the error states.
look at the time between rounds
they dont start at the same time, but right after one another
which is also not desirable
What am I doing wrong that the same steps dont reoccur... The first time it works perfectly as intended
Not sure what you're wanting. Either your rounds can possibly overlap with faulty delays or not.
Could this be because I am caching the Waiters?