#archived-code-general
1 messages ยท Page 170 of 1
Current code:
public void CalculateBulkSellPrice()
{
fakeBulkSellPrice = 0f;
for (int i = 0; i < sellCorrect; i++)
{
upgradePastCost /= 1.15f;
}
upgradePastCost = Mathf.Round(upgradePastCost);
}
what is sellCorrect supposed to be? I think for the sell function you're gonna need the amount bought in total at one point so you can calculate how much to actually add by
nvm i guess thats just how much you sell
and upgradePastCost is the cost of the latest building?
sellCorrect is finding the min value between 2 values to know exactly how much to sell
sellCorrect = Mathf.Min(upgradesBought, bulkAmount);
correct
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.
the full script
this code here doesnt change fakeBulkSellPrice
yeah ignore that
its not used in that example
but with that example selling 1 at a time works
but not selling bulk amounts
I think what you have with sellCorrect should work mathematically, i dont see any error as long as you add upgradePastCost, then divide it by 1.15
so this here?
fakeBulkSellPrice += upgradePastCost
before the division will calculate the correct result i believe
maybe its an issue of some other value being assigned incorrectly if that doesnt work
public void CalculateBulkSellPrice()
{
fakeBulkSellPrice = 0f;
for (int i = 0; i < sellCorrect; i++)
{
fakeBulkSellPrice += upgradePastCost;
upgradePastCost /= 1.15f;
}
upgradePastCost = Mathf.Round(upgradePastCost);
}
just gonna write it out so theres no confusion
yeah i got that, but still doesn't work, there seems to be an issue where when i press the button to change to the bulk amounts its changing the price
watch when the btns turn red im pressing the 1
and the value goes down?
all that the btns do is call the function to calculate the prices of all buildings
hello guys, I am a noobie of Unity. how can i make the Text above the sprite, however I tried to change the z of the Text, it didn't work at all.
im really unsure what im looking at, but id just run through debugs instead of looking at the UI. 1 issue might also happen since you're rounding the last cost. If the value rounds up, lets say u buy something for 2.8, then it rounds to 3. You now sell something for 3
true
but the price shouldn't change when pressing the bulk btns lol
might have found the issue
https://dotnetfiddle.net/VLtWYj
the math itself without rounding is fine
Test your C# code online with .NET Fiddle code editor.
not sure testing rn
i had to do some weird casting stuff in there to use floats and rounding quickly but its still pretty much the same code
yeah
oh are you assigning upgradePastCost when buying? maybe thats the difference
it looks like you're assigning it to the bulk cost, and not the cost of 1 unit
#๐ปโunity-talk or #๐ฒโui-ux
normally UI canvas is above world object
Why don't compute shaders have/use the new keyword?
the code is cut off
you wanting to support the entire keyboard?
dear lord what is this font
Whats the use case? There may be a better way
time complexity of using inputstring: O(number of key pressed) <=number of keys on keyboard
can you be specific to the "why are you capturing the entire keyboard" part of the problem space
I can pretty much only think of 2 use cases in video games for when you need the whole keyboard
- Typing/spelling games
- Emulating a sort of pseudo terminal in game where the user can type commands into it and stuff
so typically for those 2 use cases (what you wrote sounds like #1), I just have a hidden input text box they type into. They cant see the text box, but I just monitor the text box for changes and update my other visuals to match
I do the same for #2 as well actually
then you just add watching for keys for just the "interrupt" keys like Enter, Ctrl+C, pause/break, whatever you wanna actually watch for
https://docs.unity3d.com/ScriptReference/Input-anyKey.html
is this what you want for "capturing the entire keyboard"?
Thats for other languages than C#/Unity but I expect the same principle applies.
- Hidden input text box
- Force them into edit mode on it, hidden cursor
- Monitor whatever its version of "onchanged" is and utilize its new info
This also nicely automatically supports stuff like Ctrl V / Ctrl A / Ctrl C, shift-back, shift-forward, etc etc for tracking them editting it without having to rewrite all the code for how an input box works
id probably also go with some hidden text box
oh hot dawg thats nice
oh wait
its only ASCII, prolly not enough for some use cases
Probably XY problem
ah yeah, not sure what else there is tbh
Though I guess even for what I wrote, the inputString is no different, it just automatically handles backspace
I guess it also wont automatically handle ctrl+v and stuff like ctrl+c you'd have to rewrite too
yeah no Im still gonna go with hidden input box being easiest as it will substantially reduce you needing to re-invent... the input box
honestly i cant imagine any case where you would want to do this. If you want any input at all, that case would be the user typing text. The user can type text into an input field
I guess if you wanna make a visualize for like, an in game keyboard and you wanted to highlight all keypresses
hm i guess thats one very unique case lol
@frosty scroll only other thing I'd recommend is start digging into whatever GetKeyDown and friends do at a lower level.
You should be able to eventually find perhaps a lower level class that gives more direct access to the list of what keys are and aren't down.
It is ugly and bug prone.
but better than several monos in the execution order, yes.
idk how unity detect key but there is a function in c or cpp call getch()
maybe you can write a native plugin to capture all the chars pressed in one frame in other thread, maybe it is low leveler than the engine
How would this be bug prone?
Hey, I'm making a platformer and this is an example of how the rooms should be, they should always be placed randomly per level, can someone help me code the system or does anyone have a good tutorial on how I could do something like this? every room should have a prefabricated room that i created
It can be easy to be missed. missing reference exception.
Rename class name, etc.
Personally, as I mentioned I do not like to use execution order.
While I do think itd be awkward to use, you shouldnt get any actual errors in your code. You just have scripts add to the delegate chain if they want access to a pre update, and remove themselves when they dont want it anymore, or on destroy if the manager isnt null. I'd also make it a singleton/DDOL for this purpose.
If the script is renamed that really shouldnt affect anything, since your IDE will update it in every file
The only bugs that pop up would be like if someone destroyed the instance, but in that same logic someone can easily fuck up your update loop by setting timescale to 0 or disabling an object they shouldnt
How can I change the active selection on a custom editor? For example, if a text area is actively selected, how can I clear that selection via script?
Hi, I'm trying to disable and enable buttons. If I do playButton.interactable = false; it works well, but when I do playButton.interactable = true it doesnt work.
Here's the full code if needed
https://pastebin.com/1FrGBGvf
have you logged it first to see if action==3 fired
and you can use switch case
its triggered bc Destroy(quitWindow); works
(ill add the switch case)
and you can set it active or unactive to avoid the external cost of destroying it
you may try to change the color of higher constract that indicate if the button interactable.. the code seems work
Straight out of quantum mechanics, Wave Function Collapse is an algorithm for procedural generation of images. https://thecodingtrain.com/challenges/171-wave-function-collapse
In this video (recorded over 3 live streams) I attempt the tiled model and explore a variety of solutions to the algorithm in JavaScript with p5.js.
๐ป Github Repo: http...
public static System.Type[] allWeaponUpgradeTypes { get; private set; }
private static bool weaponUpgradeTypesInitialized = false;
private void Awake()
{
if (!weaponUpgradeTypesInitialized)
{
weaponUpgradeTypesInitialized = true;
allWeaponUpgradeTypes = System.AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(WeaponUpgradeBase));
}
}
i am getting an array of classes deriving from WeaponUpgradeBase. But i cant cast from System.Type to WeaponUpgradeBase i guess. How can i call functions from this?
it haves enough constract to indicate it, also it change to another scene, so if its interactable, it should change, but it doesnt
They type is different than the actual class
What are you trying to do here ?
im trying to get all weapon upgrades (classes deriving from upgrade base) then check if they can be used, if so randomly choose some of them and instantiate them
i guess i need actual class for that though
how can i get all classes deriving from base
Usually, in the Unity ecosystem, you use prefabs.
You can, however I think you would be better with prefabs.
You have list of prefabs, then you can iterate through them and see which one to actually instantiate.
Yes, that would be even better with SO.
can i make prefabs be something other than gameobjects
guess i'll make them be ScriptableObjects rather than plain classes then
I have a fishing game where you draw a renderer line so when the fishs touches it they got dragged from the first of the line until the end, but i don't know how to do this I can't put a collider the player might draw something loopy
[SerializedField] private List<GameObject> allWeaponUpgradePrefabs
private void Awake()
{
foreach(GameObject weaponPrefab in allWeaponUpgradePrefabs)
{
if(weaponPrefab.TryGetComponent(out Weapon weapon) && weapon.IsUsable)
{
Instantiate(weapon);
...
}
}
}
The best would be to have SO per Weapon then use them to iterate through instead of the prefab.
thanks for the help
what about checking the distance between last point of the line and fishes and if its smaller than an amount they get dragged
i think colliders would work better though, why not use them
How would one go about creating a scrollable panel where elements inside of it can be dragged and dropped into any position? Without strict grid etc.
Do I need to write a custom script to resize content container based on content? (not sure if this is ui or code related question)
(I have already draggable components and scroll rect working)
definitely better done as an animation, or in-code animation of a child object of the main player object
the actual player object shouldn't rotate
I assume he means that you rotate the spriterenderer, which should be a childobject of your player object
do to a smooth rotation it's as simple as:
void Update() {
if (isFlipping) {
transform.Rotate(0, 0, Time.deltaTime * speed);
}
}```
Documentation of terrain clipping, as well as my terrain and capsule collision settings. Any idea what might be going wrong?
use continuous collision detection on your player
(not a code question btw)
for dungeon generation like "Binding of Isaac" I saw something that basically said you make all the rooms in different scenes, and load multiple/many scenes at once.
Is this the best way to do that or should I be doing it some other way?
video was a bit outdated so not sure if thats bad practice now
Oh shoot. Terrain? Physics?
You don't have to use different Scenes for each Room, that probably doesn't scale too well when you have 100s of them.
I'd say, each Room should be a Prefab, that's enough.
Each Room could have a (flexible) Amount of AnchorPoints (for example, empty GameObjects) where its allowed to spawn a new Room upon completing the current one.
So when the game "starts" would you spawn in all the prefabs offset so you literally move between rooms? Or when moving between rooms you just "spawnin" a new prefab where you are and hide the old one?
In case of Binding of Isaac, you only see one room at a time.
When the Game starts, you only create one Room, the current one.
Then, when changing the Room, you could just transition into a Blackscreen, then deactivate the current Room and create a new one, and then fade out the Blackscreen
You only need a single Room to be active at a time.
I'd still recommend doing ObjectPooling on them, not plain Instantiate/Destroy
Right
Gotcha
And then when moving to a new room you disable the "old rooms preset" and spawnin the new one?
Or just spawn them all to start and disable them
h just what channel I should be in
Also re: continuous detection, it still clips through when there's a sufficiently steep slope
I actually prefer your original idea of using multiple scenes, it's more performant and more flexible
Yes, sure, having 100 Scenes for 100 Rooms is way more performant and flexible then having a single scene with a single dynamic room, sounds about right
It of course heavily depends on your project, but if it's 1:1 Binding of Isaac style, a single scene is enough
Good to know...guess the youtube series is pretty solid then, didnt realize you could just like spawnin multiple scenes at once
Always thought they would clash even if everything in the scene was offset
scenes can be loaded async, prefabs cannot
Why is loading async good? Kept seeing stuff about it but couldnt understand it
Tried to read about it but it didnt really help
Prefabs can be pooled, that's fine enough if there's only ONE active at a time, also the rooms aren't that big (still comparing to Binding of Isaac here)
because it happens in the background so the user does not notice it, no lag
The user doesn't notice anyways because the transition happens within a Loading Screen
Let's say each Room is just 8x16 Tiles and there is only ONE active at a time, Scenes seem totally overkill
Wouldnt the user still be waiting for it to load? Or you always are loading them in advance so they dont have to wait?
you would load the one(s) you want in advance but keep them in the background until needed
Interesting thanks! Hopefully I can find a good youtube video about that
@thick socket
I'd advise you to try both approaches on your own and see what fits better in terms of performance, presentation and workflow, after all there are an unlimited number of ways to accomplish this
@stark sinew 'The user doesn't notice anyways because the transition happens within a Loading Screen'
Do you realise what an oxymoron this statement is?
Did you play binding of Isaac and do you know what an oxymoron is?
Also, we're not here to argue about each other's ideas, correct? At least not in the way we currently do.
I mainly do mobile stuff, and I'd never ever want to have 100 Scenes in a Mobile Game.
The actual question could be, is asynchronous loading of a scene in addition to unloading the current one really faster then activating and deactivating an already pooled GameObject? I can't answer this.
I mean, while binding of isaac has loading screens I more meant the style of rooms so no loading screens is great ๐
How would you be able to pool it?
@thick socket
In short
Your Game could (should) have multiple States managed by a StateMachine.
The first state could (should) be an Initialization state in which you initialize everything you need, Localization, SaveData etc and do your ObjectPooling
After that, those things can be used by the other States
ObjectPooling basically means you create your frequently used Objects on Startup and disable them, once you need them you can activate and reposition them, when you're done with it you deactivate it again, very simple explanation, it can become a quite in-depth topic.
"Saving" previous for later reuse could be, for example, be done by assigning a unique ID for each room, and activate the corresponding GameObject
I guess I more mean what about the prefabs could be pooled since you need to save "previous rooms"
So I know about how object pooling works...just wasnt sure what about the rooms/prefabs could be pooled or would be worth pooling
Even if you'd only need a single instance of each room, I'd still pool them, they could be quite detailed and an Instantiation while playing the game can very well give you a noticable performance hit.
You might not have multiple instances on the screen at once, but you very well might reuse those single instances within a single playsession, why would you Instantiate/Destroy the same object over and over if you can reuse the same one instead.
My game has only a single player object, but I still don't destroy and instantiate new instances of it for every Gameplay, I just reset the existing one
object pooling is only useful when you have multiples of the same object, in your use case I doubt you have multiples of the same room
Even if I did I would need to fully save prev room incase player went back
You would only need to save the ID of that room.
Unless you want to store it's State (enemies killed etc), if that's the case then you should separate the State Data from the actual Room, because you might want to use the same Room again but in a different State
Let's say we have this order
Room 1 - done
Room 2 - done
Room 3 - Player here
Room 1 - Next
You don't want to have the next Room 1 to share the same data as the first Room 1 , but preferably you would still want to use the same GameObject for it
You could have an Initialization(RoomData roomData) method on those that you call when you're activating the Room, either passing it a previously saved one or a fresh one
I'd recommend to just find a temporary solution for your situation, experiment a bit, check out some resources, you'll get many different opinions and approaches in here that may prevent you from actually getting it done in the first place, everybody has their own preferences ๐
Gotcha thanks
Didnt realize I should be saving the states outside of the room
Try to separate Data and the thing that's working on that Data as much as possible, it'll seem tedious at first, but when you get used to it it's quite useful. Just my opinion!
For mapping the actual rooms to some IDs, you could for example use a ScriptableObject and have your RoomSpawner know about those, so it could take a random one of those ScriptableObjects, instantiate the Prefab and store/assign the corresponding ID
@stark sinew is this how you would recommend doing playerinput?
Im a big fan of SOs ๐
Let me check.. but tbh, I'm probably terrible with my Input practices ๐
I prefer an event based approach to input, I usually either have an InputProvider component that's reusable by components, firing stuff like OnSomeButtonPressed and OnSomeButtonReleased or a single InputService component that basically does the same but is globally accessible
๐
You seem to have a lot of knowledge so appreciate the help
Will see if I end up doing the scenes method or prefabs
Youtube series uses scenes so Ill likely follow that but will see ๐
Good things to know for the future reguardless
I'd recommend following the tutorial first, and when you're done with it and understand why and when it does what, you're ready to experiment with your own implementation of change the existing one!
Trying to push some custom code into a tutorial may lead to problems when trying to follow it further along
One thing that'll probably be helpful forever (not for your current situation, but in general), experiment with (different) StateMachine architectures! Feels like cheating for a lot of stuff ๐
Also, as a final word, I'd say that both the Scene and the Prefab approaches are totally valid and won't differ too much in terms of presentation to the Player, you should experiment with both and decide on your own what's good/bad about either of those ๐
Yeah I learned that following tutorial for one of my classes awhile ago
Better to fully follow and then try and change after lol
You're probably having multiple classes named BeanMovement in the same Namespace.
Check if you accidently renamed a file without renaming the actual class inside
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
It's not about the code, it's about how your Files and Classes are named
You're welcome ๐ค
Hey do you know if there is a smart way to collect the current collisions on call from a trigger Collider ?
Collider[] colliders = Physics.OverlapCollider(hitboxCollider, damageableLayer);
what you tryina do? also isn't overlapcollider a physics 2D function
you could do a query like that, or you could just keep a list or hashset of colliders
populate it in OnTriggerEnter and Exit
HashSet<Collider> currentColliders = new();
void OnTriggerEnter(Collider other) {
currentColliders.Add(other);
}
void OnTriggetExit(Collider other) {
currentColliders.Remove(other);
}```
for example^
sadly yes it is only for 2D ๐ฆ
yeah I was just wondering if there is a simpler solution, because I only need to check it once.
this is very simple
you can, as mentioned, also uise a physics query as per your example
There are other overlap methods for 3D
How can you iterate through a hashset since its unordered
hey ,idk y im getting thsi error text
im trying to make a UI with sliders
this is my codes
but i dont thin its the code issue
im not sure why im getting this error message
No line numbers please !code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class mainUI : MonoBehaviour
{
public Slider hp_slider;
public Slider ammo_slider;
private gun gun_script;
private player player_script;
void Start()
{
gun_script = GameObject.Find("gun").GetComponent<gun>();
player_script = GameObject.Find("character").GetComponent<player>();
hp_slider.maxValue = player_script.max_hp;
ammo_slider.maxValue = gun_script.max_ammo;
}
void Update()
{
hp_slider.value = player_script.current_hp;
ammo_slider.value = gun_script.current_ammo;
}
}
Also your IDE doesn't look to be configured
ois this better?
!ide
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.
Worse
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class mainUI : MonoBehaviour
{
public Slider hp_slider;
public Slider ammo_slider;
private gun gun_script;
private player player_script;
void Start()
{
gun_script = GameObject.Find("gun").GetComponent<gun>();
player_script = GameObject.Find("character").GetComponent<player>();
hp_slider.maxValue = player_script.max_hp;
ammo_slider.maxValue = gun_script.max_ammo;
}
void Update()
{
hp_slider.value = player_script.current_hp;
ammo_slider.value = gun_script.current_ammo;
}
}
```cs
Just use the paste websites for this one
thx
Looks like I'm still going to count lines xD
Np... you didn't quite get it lol
mb
oh
foreach
@halcyon tusk
You either forgot to assign the sliders in the Inspector, or your GameObject.Find doesn't find anything
Use Debug.Log to find out if your player or gun is missing
Use one of the websites so we can see linenumbers please
foreach (Transform t in mySet)```
ok, let me check
Sorry wasnt clear...how can the foreach do that if its unordered?
You can still iterate over an unordered list
Since foreach is just a fancy for loop right?
Why is
float dt = 1.0/(B+A+1);
not the same as
float3 cro = normalize(float3(B,1,A));
float dt = dot(cro, float3(0,1,0));
There's just no guarantee that the list is in a specific order
dont crosspost
internally there's an array or something
Ah Gotcha, thought you couldn't iterate through with a for loop
๐
So thus couldn't with a foreach ๐
Foreach uses an enumerator which is an abstraction
So it is different from normal for loop
But the implementation of that abstraction could still be that it uses indicrs
An example would be a linkedlist, which doesn't have indices but are just nodes linked together with a pointer to the next node
The enumerator would return the next node everytime you call movenext
But you can access a specific element using an index
hello, how do i make the camera "view" fits a certain bounds? (im trying to screencapture a character, i wrote the screencapture code, i got the character bounds, but now i need to know how to make the camera view exactly fits the character bounds, so that when i call screenCapture() it captures it perfectly (and not other objects with it)
i used ```cs
if (gun_script == null)
{
Debug.LogError("Gun not found!");
}
if (player_script == null)
{
Debug.LogError("Player not found!");
}
to check if the script are found, are they were found sicne they didnt send the message
also the slider's gameobject are assign
so im not too sure whats wrong
Check if the Object is the same name in Hierarchy
Already sorted this out by checking for Null, the objects are found, the Debug.Logs don't get called (apparently)
Idk if someone here can help me , I made a barcode scanner in unity and at first it would display my camera feed rotated -90ยฐ , I fixed that with code so camera feed displays correctly but now when I can a barcode , the barcode has to be rotated 90ยฐ ( it will only scan sideways )..
also once i remove the
hp_slider.maxValue = player_script.max_hp;
ammo_slider.maxValue = gun_script.max_ammo;
hp_slider.value = player_script.current_hp;
ammo_slider.value = gun_script.current_ammo;
the error doesnt show
so i think it might be the slider that cause the issue
If you double click on the error messages, where do they take you?
My script
https://pastebin.com/Zfx0VBC5
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.
im sorry it was that
it was the gun one
the player was fine
but i think it might be because i used a asset gun
so i change the name of the gun
and now it work
No need to be sorry!
I'd recommend to not rely on hard-coded string lookups in general, this will lead to problems if you, for example, decide to rename something
You could expose the Strings your searching for in the Inspector or use a static read-only for it, or you could change the architecture a little bit to look for the Component itself
im not too sure wat u mean in the second line
GameObject.Find("Blabla")
static readonly string BLABLA = "the name"
GameObject.Find(BLABLA)
[SerializeField] string blabla
GameObject.Find(blabla)
FindObjectOfType<gun>()
examples
oh
why do i get this error everytime i lock my pc. when i come back unity shows this and dies
so is it better to use [SerializeField] rather than gameobject.find
Does this happen in an empty project as well?
The issue is more about hard-coding the string then the method you're using for lookup, imagine you accidently rename the Gun or Player Objects and getting an Error because you need to change it in code as well
oh that make sense
my project rn it rather small, so it will be a eas fix, but i will rememebr that later on
thank u
GameObject checkBox = Physics.CheckBox(boxPosition.position, boxSize);
Issue: Cannot implicitly convert type 'bool' to 'UnityEngine.GameObject'
how to fix this
CheckBox returns a booll
you can't assign a bool to a GameObject variable
bool hitSomething = Physics.CheckBox(boxPosition.position, boxSize); would be correct
i have not tried that
I fix it
Collider[] colliders = Physics.OverlapBox(boxPosition.position, boxSize);
foreach (Collider collider in colliders)
{
GameObject obj = collider.gameObject;
}
is work now
does anyone know how to turn off whatever this is
it appeared yesterday when i restarted my computer
@rocky jackal you should! First thing would be to find out if it's an error with your project or with your device, or do a quick Google search
define "this"?
i was hoping someone would know which setting it was
at first i thought it was autofill, then i thought it was suggestions
search for AI in settings
it was off to begin with
oh wait thank you
i found the perpetrator
i don't remember downloading this
dang AI thinking i don't know how to code D:<
this is included inside C# DevKit
VSC intellicode not as good at VS community intellicode
okay
thanks
need help with photon.
Im trying to run c PhotonNetwork.InstantiateRoomObject("flamethrower", playerPos, playerQuat);
the prefab "flamethrower" isnt in the Resources folder, how can i load it?
thanks
Hey I'm new to programming so I find it challenging at times. I have a problem and I would love a solution can y'all help me?
Problem: I have a game where enemies follow you and when they are close enough they attack. Is there a way to code that whenever they attack they perform a specific animation ( attack animation)?
So my ui canvas is set to Screen Space - Camera
and i am trying to set an image's transform to my mouse's position
but it keeps getting set to absurd numbers like 7000 on the z
anyone got an idea
using System.Collections.Generic;
using UnityEngine;
public class Crosshair : MonoBehaviour
{
void Update()
{
Cursor.visible = false;
transform.position = Input.mousePosition;
}
}
any ideas?
hello I'm something new, is there a way to imitate the grab, drop and throw objects from half life 2?
General questions go in #๐ปโunity-talk
Sorry there, didn't check autocomplete, was wrong channel
you mean the gravity cannon
Whenever you call the attack method, use one of the animator methods like SetBool, SetTrigger or just Play to cause the animation.
Look into how the animator works to understand what I said better
You can tag them in the correct channel if you want to answer
okie will do! thought they wanted to know how to code it
It's much simpler to do with hinges and/or spring joints
i think rectTransform.anchoredPosition = Input.mousePosition;
can somone help me with something?
ok
Assets\Crosshair.cs(10,9): error CS0103: The name 'rectTransform' does not exist in the current context
you have to make a reference to Rect Transform component
private RectTransform rectTransform
void Awake(){
rectTransform = (RectTransform)transform;
using System.Collections.Generic;
using UnityEngine;
public class Crosshair : MonoBehaviour
{
RectTransform rectTransform;
void Start()
{
rectTransform = GetComponent<RectTransform>();
}
void Update()
{
Cursor.visible = false;
rectTransform.anchoredPosition = Input.mousePosition;
}
}
it doesn't move it
at all
So is not particulary about coding but i don t know who to ask so i made a tilemap and after you make the tilemap you have to go to your sprites and put the pixels you have, on the sprites but i have 16x17 tiles and if i put 17 is space and if i put 16 they go into each other i have to remake the sprite or i can make it somehow.
it's not a code question it should go in #๐ผ๏ธโ2d-tools
ok sorry
also I think you are asking about PPU sizes ye
You are just moving the anchor there, I think.
Also you can cast transform as RectTransform, don't have to get it as component
then what can i do
UI space has consideration depending on canvas mode, types of anchor. If you want to keep it simple and place a sprite in world space under mouse like you initially tried, you need to convert mouse position from screen space to world space. https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
that isnt what i am trying to do. i am setting a sprite in the canvas space to my mouse position, which would be 1 for 1
e.g (1920, 1080) with my mouse would equal (1920, 1080) on my sprite
image, not sprite*
You are not converting anything here
I want to make a game with 4 different cameras, 1 in each corner, how would I do that
cinemachine would be your best bet
Does it have something in it already for that
and i do not want to. I want to set an image in the canvas to my mouse's position on the screen, not in the world
Also check your input. https://docs.unity3d.com/ScriptReference/Input-mousePosition.html is a normalized range 0-1
ah nevermind, when when converted to screen space
Another thing to consider if you insist in working inside UI, make sure you are not using reference resolution. Because local Canvas position will be using it
btw is your camera in Orthographic view ?
You should post your complete question as well, with all detail what you are trying to do.
yes
Thanks
yeah idk
afaik
rectT.anchoredPosition = Input.mousePosition;
should work but idk why its not, it adds offset for me rn.. i forgot what I did last time xD
Nevermind
fixed it with some help of ai
this works:
using System.Collections.Generic;
using UnityEngine;
public class Crosshair : MonoBehaviour
{
RectTransform rectTransform;
void Start()
{
rectTransform = GetComponent<RectTransform>();
}
void Update()
{
Cursor.visible = false;
Vector3 screenPoint = Input.mousePosition;
transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
}
}
minus the start function
dont need that
you were told to do this already though and you argued it ๐คท
works
thanks mate
move this conversation to #๐ปโunity-talk
RectTransform rectTransform = (RectTransform)transform; to get rect transform
So I have a loadasset script right to load assets, and im referencing it in another script so I can load a object from assets, how can I get the gameobject it spawns in this other script so I can set its spawn position
which method is you using to spawn it in/
if it's Instantiate you can already input the position in those params
the function returns you that object
Anyone know why my perlin noise is not consistant across terrain neighbors?
private float[,] GenerateHeights(Vector3 position)
{
float[,] heights = new float[terrainSize, terrainSize];
// This factor helps in controlling the frequency of the noise
float frequencyFactor = scale / gridSize / terrainSize;
for (int x = 0; x < terrainSize; x++)
{
float xCoord = (position.x * terrainSize + x) / scale;
for (int y = 0; y < terrainSize; y++)
{
float yCoord = (position.z * terrainSize + y) / scale;
heights[x, y] = Mathf.PerlinNoise(xCoord, yCoord);
}
}
return heights;
}```
Don't use ableist slurs, please.
Do I even have that script right
Will this load a object from assets and put it into the hiearchy?
no
shit
you would need to instantiate it
could you tell me how to do that?
thanks
I just don't get it, because the noise should be continuous over these terrains:
I tried setting the parent of the loaded asset and it said its disable to prevent data corruption
its also not setting the position right so it looks like im not referencing the loaded object right
what are you trying to do and what is the point of even going through all this trouble for Resource method? it's almost useless cause it only works in the editor anyway so you mind as well make references to prefabs
im trying to spawn a object from the assets, set its parent and position
chances are you are trying to modify the one from resources and not the instance of it
no thats not where it goes at all
oh
and ur still returning the asset from resources
Like that?
var objectInstance = Instantiate(LoadObject.Loadassset(assetName), position, Quaternion.identity, parentGoesHere)
ohh
Take a look at what the Instantiate method does
haha it works
i think i finally finished my script
or system
its multiple scripts
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
https://gdl.space/nihabopule.cpp
I'm not sure why this isn't working, I feel like something is being used by all 4 players in the code that each player needs its own version of, but I don't know what.
Are terrain heightmaps 0,0 in the bottom left corner and size,size in the upper right?
lol, heightmaps are indexed y,x
Ok
yo. can someone help me, i have this cat ai, and most of the functions are there, but im trying to add the Pathfinding thing, but after i did, the cat wouldnt move, is there something wrong with the code, or is the Nav Mesh
(the functions of the cat so far are, follow, stop at a certain distance from the player, and run away from the player if the player get too close to the cat)
using UnityEngine;
using UnityEngine.AI;
public class CatController : MonoBehaviour
{
public Transform player;
public float stopDistance = 2f;
public float startFollowingDistance = 4f;
public float runAwayDistance = 1f;
public float pathfindingDistance = 6f;
public LayerMask obstacleLayer;
private bool isRunningAway = false;
private NavMeshAgent navMeshAgent;
private void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
navMeshAgent.autoBraking = false;
}
private void Update()
{
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
if (isRunningAway)
{
if (distanceToPlayer > runAwayDistance)
{
isRunningAway = false;
}
}
else
{
if (distanceToPlayer <= stopDistance)
{
isRunningAway = true;
}
else if (distanceToPlayer >= startFollowingDistance)
{
isRunningAway = false;
}
}
if (isRunningAway)
{
Vector3 runDirection = transform.position - player.position;
Vector3 runPosition = transform.position + runDirection.normalized * Time.deltaTime;
MoveTo(runPosition);
}
else if (distanceToPlayer <= pathfindingDistance)
{
MoveTo(player.position);
}
else
{
navMeshAgent.ResetPath(); // Stop moving
}
}
private void MoveTo(Vector3 destination)
{
if (navMeshAgent.enabled)
{
navMeshAgent.SetDestination(destination);
}
}
}
@cunning meteor Don't cross-post. Not a code question. Not a Unity question even?
you code in visual studio
For unrelated tech questions #497872469911404564
Anyone want to look at my terrain generator script and see why the terrainlayers aren't being applied and all I get is glorious pink?
private TerrainData GenerateTerrainData(Vector3 position) {
TerrainData terrainData = new TerrainData();
terrainData.heightmapResolution = terrainSize + 1;
terrainData.size = new Vector3(terrainSize, 10, terrainSize);
terrainData.SetHeights(0, 0, GenerateHeights(position));
terrainData.terrainLayers = terrainLayers;
// Create an alphamap based on the heights and apply the terrain layers
float[,,] alphamap = new float[terrainSize, terrainSize, terrainLayers.Length];
float[,] heights = terrainData.GetHeights(0, 0, terrainSize, terrainSize);
// Initialize alphamap to zeros
for (int i = 0; i < terrainSize; i++) {
for (int j = 0; j < terrainSize; j++) {
for (int layer = 0; layer < terrainLayers.Length; layer++) {
alphamap[i, j, layer] = 0;
}
}
}
for (int y = 0; y < terrainSize; y++) {
for (int x = 0; x < terrainSize; x++) {
float height = heights[x, y];
// Determine the layer based on height (modify as needed)
int layerIndex = 0;
if (height < 0.3f) layerIndex = 0; // First layer
else if (height < 0.6f) layerIndex = 1; // Second layer
else layerIndex = 2; // Third layer
// Check for index out of range
if (layerIndex < terrainLayers.Length) {
alphamap[x, y, layerIndex] = 1;
}
}
}
terrainData.SetAlphamaps(0, 0, alphamap);
return terrainData;
}```
I'm using the new Unity Extension for VS Code, but it doesn't seem to be linting any of my errors. I've tried uninstalling and reinstalling VS Code, the extension, and the Visual Studio Editor 2.0 package but no luck. I've also tried regenerating the project files. Any ideas what I could do to fix this?
!vscode
I've followed all these steps without any luck.
show which version you installed from package manager
You sure you followed all of them?
Not just the first part?
Did you launch the Installer, click modify, and install the unity package?
Hmm, I tried to load that VSC Unity plugin and it says my csproj (created by Unity) is in the wrong format: is in unsupported format (for example, a traditional .Net Framework project). It need be converted to new SDK style to work in C# Dev Kit.
thats VS not VSCode
you need to install the new Package inside package manager
Microsoft has released a VSCode extension for unity which no longer requires you to go through a a painful process to get code completion , error highlighting and intellisense working.
original guide:
https://code.visualstudio.com/docs/other/unity
Unity for vs code:
https://marketplace.visualstudio.com/items?itemName=visualstudiotoolsforunity.v...
Yes, I followed all of them.
Yes, I tried restarting it after installing and regenerating.
You rock, that got it working perfectly. I was just ignoring the VSC errors and using Unity for errors and warns.
glad it was of help
idk if this is the right place to ask because this seems to just be a unity editor problem but something really weird is going on with this collider:
im not able to change the Y offset because the center always moves in the opposite direction
ive disabled all the scripts and stuff on this object
some step you def missed out somewhere
Press Z. Make sure your tool handle position is set to Pivot not Center
im trying to change the offset in a script and its doing this same thing
i was just trying to narrow it down
it even does it in the editor
changed it to pivot and theres no difference
Does this object have a parent with negative scale?
Or does it have negative scale itself
it needed to be rotated to face the camera properly
Put the mesh renderer on a child object
And rotate that
Or fix your mesh/ export it properly in blender
oh that would work yeah
i didnt want to do that because i have to scale it up a ton but thats less annoying than dealing with this
thanks
In either case putting the mesh renderer on a child object will make your life easier
alright ill keep that in mind
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I went through all the steps, and it's still not working right. Some things work, like it suggesting Start().
But when I make typos, it doesn't underline them in red.
I mean VSCode integration is known to be kinda poor
spot the difference
It's not really supported
screenshot external tools in Unity
and do you have messages in the Output in VSC panel?
No messages.
well that is weird then, it should either tell you it loaded C# plugin or says errors with csproj
The new extension actually works great, at least most of the time since it literally just came out
eh I wouldn't say great, the intellicode is still garbage
I type Serial it writes [SerialSerializeField] for me
Yeah its a bit buggy
still needs work but the process is less butt hurting than before
I think it's supposed to use Intellisense (the one from VS)
the whole disabling modern net bullshit
glad all that is gone
its not 1.0 yet so there is probably still bugs
I see in your video you have Output set to "Projects". On mine, I don't have the option to set it to "Projects".
idk if that part is important, unless until its connected
btw do you have .NET installed ?
Like this?
nah the one from the website
i would not use extension for that
I'm not sure. Installing in case I don't.
one way to check
dotnet --info inside command line / terminal
dont forget to restart pc ๐
Just reinstalled it and restarted, but no luck. I'm on a mac, maybe that has something to do with it?
I also wonder if maybe it's working, but I have some setting wrong in VS Code.
hmm only thing I can think of is delete the csproj files in your project, regen project files then double click a script and open it, then check the output view or look out for anything after like any messages popups
where can I find the csproj files?
its in the root folder of your project
hi,
if I have a list of 3 but i want to make it a list of 10 with all extra values to be 0 , do i need a forloop for this or is there is a better solution ?
loop/LINQ is how you would typically interact with list many items
idk what you mean though by "Extra values to be 0"
0 what?
what type of list
like item number 4 =0 , 5=0,6=0 ...10=0
list<float>
so how are you adding elements to this list because float default is already 0
can i just check if the list is less than 10 and if it's just add items of 10-count with the value of 0
like how we would do on the editor if we change the value of the list , it adds items to it and set its value to be default
The default is 0 so you can probably just addRange a new collection, with the size of 10-count
No need to loop
I did this and this is the message I got, but I'm not sure if it's related.
could you show me a code please ?
no not sure whats going on here , idk if u saw my vid but it should either tell you it loaded the c# project or something went wrong, are you able to select Project tab?
Google addRange, I'm on mobile
got it thanks โค๏ธ โค๏ธ
i guess You could just use a superior and actually good working IDE
use visual studio community
call it a day
There is no project tab on mine. These are the options.
yeah something in there borked but idk how you would fix it, I don't really use VSCode I'm on VS2022
The whole reason I was trying to switch to VS Code is because that one wasn't working for me haha
really? works great for me, much better than 2019
granted not as good as windows version but works goood
I have an ScriptableObject.
Inside of this ScriptableObject, i got some AssetReference's and Methods to load & unload Asynchronously like this:
`public class X : ScriptableObject {
private AssetReference asset1;
private AssetReference asset2;
private List<GameObject> whichAssetsLoadedList = new List<GameObject>();
public void Load(GameObject loadedBy){
asset1.LoadAssetAsync();
whichAssetsLoadedList.Add(loadedBy);
}
}`
What i am trying to accomplish is:
I want to create a Base of Loadables.
In that base, i want to make Load() Method and whichAssetsLoadedList List to be required.
I tried Interface but List cannot be private. I tried Abstract class but i want only one class. Like, if i use an abstract class, i will need to use different Abstract class with same thing. Like one for ScriptableObjects, one for Monobehaviour with same Codes in this abstract classes and so on since Abstract classes blocking to add another class in it.
But the Loadables base must take UnityEngine.GameObject. Idk my brain is burned out. Someone can try it? Oh wait what if i create abstract class with UnityEngine.Object but no. IDK
Any idea?
all you need is this on Macos and ur done
Ok, I'll try this.
Interesting, what's the use-case?
Do you want to make your own Asset Loading System for Runtime? Or is it something for Editor?
Also, what's the problem you're facing?
You want a Base for something that could be inherited as either a ScriptableObject or a MonoBehaviour, but interfaces won't work, correct?
Instead of having a List Property in your interfaces, you could use a GetMyList method, the MonoBehaviour base and ScriptableObject base could implement them in their own ways, but they're safe to have them, that way you could keep the underlying list private and return a readonly or copy
I want to make a crafting system that is basically X + Y = Z essentially.
For my game the player can collect many of each item type. A lot of the tutorials I've seen utilize an inventory with a list of scriptable objects. Which I think would be fine if you don't have a ton of items in an inventory, but I would end up with a list of potentially thousands of scriptable objects.
Are there any better methods for an inventory and item system where you can have the item in the inventory and then an associated value of the total # in the inventory?
Firstly, i am loading this ScriptableObject X. After that i want to add to the list which object OR which handle loaded this SO thats it. That way, i can "Unload" that asset directly without actually making many calculations. But what i want is Reuseability.
Yes i tried Interfaces but List cannot be private. I dont want the List to get overriden by something else.
GetMyList? Amazing idea. I should give a shot.
Keep a private List on the Implementation Side and return it in that interfaced method
Is using "ref" keyword is necessary for that GetMyList? I heard C# automatically does that.
ref? In what situation? ref is afaik only used in combination with defining/passing parameters/arguments, in methods
Do you mean return?
PSEUDO CODE
MyInterface
List<GameObject> GetList()
MyClass : ..., MyInterface
private myList
List<GameObject> GetList()
{
return myList
// return myList.Copy()
}
Hm better i go test this :d
Yep! so it returns a copy in that code? Better i go test that too
You can use anyList.Copy()
Although, if the list contains classes, it doesn't actually copy those, so they're still the same GameObjects inside, just a different List referencing them
You can't, it's an Interface Member
i heard c# 8 also allows that tho in what situtation it does? idk.
What exactly do you want to do as the end result?
Not in code, I mean, when that thing is done, what is it supposed to be?
The only idea behind Interfaces is it to provide a public set of functionality that can be referred to while allowing to abstract the actual implementation away, without using abstract classes or class inheritance at all
In my own bad wording
So there will never ever be private stuff for interfaces, you can't even declare access modifiers there, they're always public members
Bad wording? A nice explanation.
What you eventually want is
A property with a private setter
But idk, asking for the final goal again ๐
Ah, I think I got it, you want to know which Thing is loaded by What other thing? Hence, the loadedBy?
Ok!
I want to get Which objects/loadhandles loaded this SO. If its a loadhandle, i can release this SO from memory or decrement to ref count. If its a gameobject, then i will remove from the list, and release this SO like that. But a reminder there is Reference counts. Since i cant get Reference count in runtime, i will use this list
So basically, multiple other Objects could have called Load on that SO instance and you want to keep track of them?
I'm assuming those ScriptableObjects are created at runtime, and you want to destroy them when the list is back to empty again?
Yes. I want to destroy the AssetReferences and itself. So if list count is zero it will unload. If its not, it will decrease the ref count. If it gets loaded again, ref count +1 and assets are here. Another one calls Load then ref +1. I am using Addressables tho but they dont provide any ref count. If they had the "get" ref count of that object, it would be a kid toy
Aaaaah, I just googled what those AssetReferences are, just noticed you're doing something with Addressables, never touched that system so far
But I understand further I think
Do you want to unload those Adressable part once it's no longer used?
yes
sir
This thing is public
i mean idk u said it will be public but um how will i save from other objects 
Oooh, you want the List to not be accessible from outside at all?! My bad, then an interface isn't the thing you want
abstract the way right? You should try in a empty project man lets solve this thing lmao! A base class with private list but allowed in use of ScriptableObject, Monobehaviour or Any type of GameObject. Impossible? idk

I know finally got what you're trying to do...... I've scrolled up again haha
Basically, in very simple terms, those ScriptableObjects are Spawners (for Addressables) and you want to keep track of the SpawnCount, unloading the Adressable when the count hits 0
Why do you need a ScriptableObject AND a MonoBehaviour Base in the first place?
So they have a shared functionality of accessing that Spawner SO?
Ohooo i scrolled a lot tooo ๐ญ
ScriptableObject contains AssetRefs in it. It is on use in loaded objects.
I dont need a base. If i cant do that, i will use Abstract classes for each
But i am gonna use this trick later on so i thought a base would be a star.
Second line seems so attractive to me right now 
What if i use another SO for that list? Lets think about that
Honestly my head went out, it seems so overcomplicated to me
I have no idea how Addressables work, not even a little bit
So if i create an SO like "LoaderSO" like this:
`public class LoaderSO : ScriptableObject
{
private List<GameObject> loadedBy = default;
// For testing
private void AddToLoadedByList(GameObject signalObject){
loadedBy.Add(signalObject);
}
private void RemoveFromLoadedByList(GameObject signalObject){
loadedBy.Remove(signalObject);
}
private System.Int32 GetCountOfLoadedByList(){
return loadedBy.Count;
}
}`
It actually solves my problem. This list reference will be gone after unloading the ScriptableObject X so no memory leaks will be seen if i am not in my dumb time
Nice!
But if it's only the ref count you need
Why store the GameObjects instead of incrementing and decrementing a counter?
Ok, I answered it myself, it's useful to see which GameObject forgot to unload something
myList = default should default to null btw, doesn't it? ๐ฑ
Nice question! I actually thought about this for so many mins and decided to really add UnloadAll() thing. I wanted to notify other objects that this ScriptableObject unloaded. But rn it seems counting will work for now
omg lets test it
ur right
i think today i am done.
Thank you for helping me sir. I will think about the ScriptableObject solution and see if its compitable with my project. If its not, i will think about Abstract classes or actually using Event based things again...
You're welcome! Wish I could've been more helpful, stupid Addressables q.q
Could you guys help me figuring out why my character controllers are only colliding each other for a few frames, then walking thru each other?
I'm using CharacterController.Move every frame, and I'm also using a down raycast to adjust the character height when it falls below the ground level.
hey, I've got a simple playmode test in place where I load a scene and then find objects in it, but for some reason FindObjectsOfType returns 0 (although the activeScene in debugger variable has these objects listed) - any help?
Switched to this and it's working. Thanks for the advice!
It looks like you're using DOTS, soo, just making sure, these ARE gameobjects, not entities, right?
It looks like you're doing Hybrid, so that's a longshot
Hi ๐ Im practising 3d movemet and stumbled across this part of a code on the internet:
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
What does this part do? What is Mathf.Sqrt and why are we multiplying with -3f?
Dooes anyone know?
Its from this piece of code https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
Im trying to make a stamina bar for my game, and I found this issue. When I start the game and run around and pause while the stamina bar is on screen, it doesnt disappear. It also gives me this weird error and after the error occurs I can't look around. Here is my stamina script: https://hastebin.com/share/anacarewaj.csharp. And here is a video of it happening: https://streamable.com/n2p4wk. (In the video the weird error doesnt happen, if it happens again ill show what it says)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hmm, idk why it's -3, it could just be -jumpHeight (still needs to be negative to counter gravity). The Sqrt doesn't really seem necessary either, it simply has the effect of sharply reducing y velocity as jumpHeight increases
FixedUpdate is meant for applying physics forces, you should just be using Update here, but if you Debug.Log(menu.gamePaused) is it true? Also are you sure the staminaBar image is a child of the group element?
Anyone know anything about accessing mobile camera?
Dumb question but does Unity have some sort of math function that converts negative numbers into their 360 degree angle equivalents?
Like for example, -50 would be represented as 310
This works but I dunno if theres a cleaner way ๐ it bugs me for some reason
Right now I have a pretty small prototype that is just one level/scene, that the player can retry many times. For this I have the following line:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
However I notice that after 15ish minutes of continuous play, the game starts to get laggy. When I alt+f4 and restart everythings back to normal.
Are there any common reasons why this might be happening?
Thank you
Is the game laggy or your editor? Does it continue to lag even if you stop play mode and re-enter?
This happens even when I build and run the .exe
When using the editor, stopping and restarting fixes the lag as well
I'm just confused by you alt-f4ing. Does the game lag every time you start it again in play mode (not built, in the Unity editor) after the first time it starts lagging?
I alt-f4 when playing the .exe. In the unity editor, restarting fixes the lag
I don't see a reason why that line specifically should be causing the lag. Is your scene being properly cleaned up each time you reload it? You aren't having objects sticking around from previous scenes, or 'persistant objects'?
It sounds to me like something is not being destroyed when you reload the scene, causing it to pile up memory over time
Causing the lag.
You say after 15 minutes, which depending on how complex your game is, sounds about right for a memory leak to form
Right, is there something I should do to make sure things get cleaned up?
or like what type of things tend to not automatically get cleaned up when reloading a scene? I'm assuming some or most things are cleaned up
I would first look into each of your objects you're using consistently through the scene, and watch your hierarchy during reloads (so play in the editor, not in a .exe) to see if anything is sticking around that shouldnt.
It can be a complex issue to solve and I'm not exactly sure what's going on in your game, so I can't offer much more advice on the issue -- but from what you're describing, that sounds just like a memory leak from reloading the scene or scene objects improperly. You can also check out the Profiler to get a better idea of what's causing the lag -- definitely look there next.
My first hypthesis would be that I call the overlapCircle method many times. Each time the results get stored in a list of Collider2D, and I check if the size of the list is 1 or 0
although that List is scoped within the method
Yes, I would definitely go over any object lists or any other collections. Accumulating such data without disposing of it could be the source of your problem.
I see. So if I have a method that gets called often, and it creates a list, I should dispose of the list at the end of that method? How do I do that
I kind of assumed it would just be garbage collected or something
How do you dispose of that kind of stuff?
It really depends on what the problem is. If it's a DDOL object you'll need to make instances for example. Object lists that persist through loads could be changed instead to some other data type, then recalled when needed. It's a bit of a broad topic.
you cant reuse the list?
No you can totally reuse lists. I'm just referring to the fact that Popine may have a list that is collecting data without resetting it when he needs to (on load), which might be causing his issue. It just depends what's in your list, how big it is, how often it's being called upon, etc.
Just because he mentioned it.
If a list is a field in a class and the class instance is destroyed the list is also destroyed, right?
Ok new hypothesis, I create a coroutine every time the player hits the enemy. Maybe that's a problem? I notice the lag that accumulates mostly happens when the player hits the enemy. I tried adding an extra yield break; at the end of all my coroutine methods, I'm not 100% sure if that fixed it but it seems like it's improved
if its coroutine related more likely its multiple coroutines trying to work on the same data at the same time
interesting. I'm pretty sure I dont have any conflicts like that. I'll have to learn how to use the profiler tomorrow
what I normally do is I make a private coroutine variable. Then:
if (myCoroutine == null) myCoroutine = StartCoroutine(MyFunction);
this way duplicate calls wonโt start a coroutine while it is already going
yes never make couroutines for gameplay behaviours it sucks
make a float timer using update to prevent more attacks
"Never" is quite an extreme, coroutines are useful in their own way
That seems like a pretty broad statement, no?
and i wrote never for gameplay behaviour. not just never
honestly it's a pain to debug, and not quite performant.
If it's for UI it's fine
or anything else not "gameplay related" but it's expensive
My statement is still the same, they have their use cases
a single coroutine isnt gonna cause you any lag whatsoever
i mean lag whatsoever is for networked games, that shouldn't be in beginner code sorry.
but to make my point, don't make an attack with a coroutine it's bad
i mean lag whatsoever is for networked games, that shouldn't be in beginner games.
What does this mean?
I have even less of a clue now what you are trying to say
lag is for networked games??
singleplayer doesn't get lag it gets freezes. singleplayer is framerate reliant, networked games is both framerate for clients and ping reliant and that's not even on point on the issue so i will stop replying before i get banned for no reason and spamming
lag is from ping
I'm not trying to be rude but your definition of lag is not how it's used by most people
Im also not trying to be rude but you are just wrong
inconsistent and low framerates and frametimes are absolutely considered lag
and i'm not saying coroutine will make this lag
i'm saying don't it's not best practice
what needs to be profiled must be profiled, but codewise that's kinda wrong
If everyone only used what is considered best practice nothing would get released
saying "don't do x it's bad" is very broad and definitive
List of things people said is slow/bad (in comparison or just in general) and shouldnt be used
If statements
Reverse for loop
new input system
string.contains
unity running on 1 thread
any while loops in update
ints
Truly nothing would be coded if people followed this logic
i don't care also about slowness, the hard things you would have to debug is collision issues after it
or errors or things you won't get out of it, but anyway i won't speak anymore
i don't have anything to prove here
I mean, it's not really hard to debug though. Are you using the actual debugger with breakpoints?
i make multiplayer games and i can debug my own things
and that's not about the issue again
I am genuinely curious what kind of errors you would get in a coroutine that you wouldnt get in update
i don't have any
Or what collision has to do with this at all
So two things you said (it being not as performant, and hard to debug) are now not the issue. I'm confused, what IS the issue?
And yeah, what do collisions have to do with it?
collisions are fine, but you could #1 lose references while the coroutine finishes etc...
im declaring an enum in one file, and want to have multiple other files inherit from it. For whatever reason I feel like this is wrong? is this fine?
Really depends on context but if you wanted just a general vibe check, that seems like something that would be done yeah
or any other issues while it's going on, if you would just use ontriggerenter2d or 3d, and update with a cooldown, you would be way better
this really sounds like you're doing something wrong instead of it being an issue with the coroutine.
i'm not the one having an issue again here
so i'll stop talking
because eh i know how right i am anyway
Well I actually am questioning if theres some real issue with coroutines, for my own knowledge. But all you've done is present statements then take them back, then change the context, now you're doing something with collisions and losing references? I just think you're trolling at this point
coroutines are fine, when used correctly is what i've said
That's the confusing part
"The problem is x"
"Again, I'm not saying the problem is x"
you're just trying to have a point when i'm just trying to help someone why should i care
Completely unrelated to what homie is talking about, But I have heard from a bunch of people that third party implementations of couroutines are vastly better than Unity's built in ones
you can place the enum in its own file, although im not entirely sure if this is what you're asking
ah thats interesting, might check some out
im aware, but then when I try to use it in other files it makes me do "using static <filename>" so im not really sure
i dont like using stuff i don't fully understand
you dont have to if its a public enum, you can just use it then unless you are referring to some namespace issue
MEC coroutines specifically is supposed to be very good
and my point was just you're going to have way more trouble debugging and guessing what's wrong when you use them
when i used an example you where smoking weed going out of subject too
you sure? since currently i have it as a public enum and it requires me to do that.
yes, its the same as if you declare a public class
Wow
Enums are inherently static, because you don't change what they are ever. This means you can reference them from any script without a reference because the programming gods know they will never change
A variable of that enum can and will change (kinda the whole point). So it needs a reference like most things do
Make sure your enum and the class its inside are both public, if it's still a problem there might be some odd hiccup in your c# project file or something
Yea im adding coroutines to my list now of what people have said is bad. Maybe ill title it to be more encapsulating
also you can only have one at one point running in, so if you use it for multple things, the other one will have to wait
No?
meaning for gameplay it's real bad
no
Not that I don't trust you guys, but im just confused as to why its doing this?
Item.Behavior
yes?
Becuase it's not native to that class ๐
your enum is current inside a class, it can be in its own file*** entirely
that makes a lot of sense yeah!
this isnt even related. for your own reputation yea maybe stop talking lol
just to elaborate on what i'm using coroutines for, since i have no idea if its "bad" or not.
Basically I want the player to freeze for a few frames when they hit the enemy (hitlag), to give the impact more weight. So when a hit is detected, I start a coroutine that records the current velocity of the player, sets the velocity to 0 for several frames, then sets the velocity back to what it was originally. That's all it does.
do i get rid of the class stuff? theres nothing other than the enum in that file?
lmao why remove it then
i'm out
its like having a Matt in your english class but you know a Matt from another school or something, since that other Matt isn't inherintly known by the class you gotta specify which matt it is ๐
my sentence wasnt directed to you dude. I said "bad wording" because i wrote class instead of file in the message above ๐คฆโโ๏ธ you really are clowning right now
I could refactor to not have to use coroutines for this, but I figured it would be harmless
I dont entirely know what this is for, so i dont want to suggest getting rid of the entire class. I was just stating that the enum can exist outside your class and everything can reference it
that sounds fine to me
just keep track if a coroutine is already started
Coroutines are absolutely fine to use. For behaviour or anything
There are pitfalls
also I tried adding a GC.collect() call before the loadscene, and that didn't fix the problem. Would that rule out a memory leak?
You just have to understand them and take care to avoid them
When I use Coroutines I usually use a template like this
Coroutine coroutine;
void StartStagnate()
{
if (coroutine == null)
coroutine = StartCoroutine(Stagnate());
}
void StopStagnate()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
coroutine = null;
}
}
IEnumerator Stagnate()
{
yield return new WaitForSeconds(detectionStagnateTimer);
detectionStateToggle = DetectionState.Decreasing;
}
Might be a better way available but works nice for me
what are you trying to do with this?
is the StopCoroutine() call necessary? Maybe that's what i'm missing. I imagined it would stop once it reaches the end of the method or yield break
For gameplay reasons I need to kill coroutines early sometimes
It depends, sometimes you want to run a coroutine and not allow others to run while 1 is running. Sometimes you want to restart the coroutine (maybe in your freeze thing)
I was thinking if I manually trigger the GC, there wouldnt be any chance of something accumulating over time that would cause problems eventually
Did you post your code somewhere above? maybe i can see whats wrong, i imagine you are probably just starting a shitton of coroutines
you could always use UniTask is perfomance is a concern
{
Vector2 currentPosition = gameObject.transform.position;
Vector2 currentVelocity = rb.velocity;
animator.speed = 0;
for (int i = 0; i < frames; i++)
{
gameObject.transform.position = currentPosition;
rb.velocity = new Vector2(0, 0);
state = new State(state.GetName(), state.GetFramesInState() - 1, state.GetDirectionFacing(), state.GetAttackId(), state.HasHit(), state.GetChargeFrames());
yield return null;
}
animator.speed = 1;
rb.velocity = currentVelocity;
yield break;
}```
can you show the full relevant code, like where you start this coroutine. That part is probably more useful to this
on a paste site ideally
other than the state thing, which idk what thats for, this seems fine
basically I have a method in fixedUpdate(), which checks if the player's attack overlaps with the enemy, and if it does, calls this method. Then it sets a boolean to make sure it can only happen once per attack
well actually I set the boolean before starting the coroutine
instead of describing it, just show it. there might be a difference in what you think it does vs what it actually does
well it's kind of spread over a few different files
if you're thinking that the method might be getting called way more often than expected, I can try printing a log to show it's only happening once in a while
you can still show a snippet of the relevant line, but if you rather not, id just suggest doing what was written above in the example of starting a coroutine only if your stored coroutine is null. Or killing the current coroutine and starting a new one, depending on the effect you want
yes also just throw a debug in there
yeah i'm certain that too many StartCoroutine() calls is not the issue
and i never said it was
at least not in a short amount of time
i said to profile it
its hard to really suggest anything then since ive only seen the coroutine. Other than state, all of this clearly wont cause any issues
You can use https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html
if you want to see custom profiling on which part might be causing issues
thats at least good to know though thx
Can I ask, what's your opinion on Jobs?
Or Tasks?
they're good too, when used when it's supposed to
like your cpu is overloaded on a single core for example from a single method call
it all depends on the usage but singleplayer needing that is... rare and networked games too i guess
i'll get a profiler screenshot just gotta play the game for like 10 minutes before it start lagging
how much is too much to store in playerprefs before I should start saving by other means?
...I'm about to add over 300 integers to it. And this seems like maybe it wasn't designed for that.
sounds like trouble, considering you'll be autogenerating the names (i really hope you are at least). Id just move onto other means after you start needing to save anything except player settings
https://docs.unity3d.com/ScriptReference/PlayerPrefs.SetString.html
this is the only limit im really aware of
Keep the value at 2 KB or smaller. To store larger amounts of data, write them to a file in Application.persistentDataPath.
Im sure the same logic would apply to your 300 ints, even though its not 2KB its still a lot of numbers
honestly don't use playerprefs at all just save a binary save file inside persistentdata as he said
or database if needed
Hi guys! I have a problem with linerenderers and canvas
I have a canvas set to screenspace camera and some linerenderers drawn by code. The problem is the lines appear above the UI panels
I've tried with sorting groups and changing Z (if I change Z of the lines below -10 they don't get drawn but that's all) and no luck
the sorting layers
this panels are in BottomMenu and the Lines in DrawingLines
Thanks in advance ๐
So, I have a script which breaks glass into around 100 pieces, but it has become pretty obvious to me that this causing little lag spikes every time the script is ran. So my question would be, performance wise, what should I do to make it perform better? Currently, For every glass shard I make a new game object and give it a mesh collider&filter&renderer. This is obviously slow, so I have a couple ideas, but I don't know which I should do, or if there are better ways to do this since I have no idea how fast/slow these things really are. One idea is to never destroy the shard game object, but rather remove/disable it's components and mesh and re-use said game object, and another idea is to also make like a hundred new game objects ready before the start of the game and once they get used and there is less than a hundred spare game objects, slowly make more of them. The problem I feel with the first one tho is that, would it even be faster to disable/destroy everything in the shard game object and re-use that over just deleting/disabling the shard and making a completely new one?
Pooling objects is generally always faster. I would avoid having to do component swaps if possible.
I got an Audio System. This audio system adds a Monobehaviour Component to inside the GameObject if the GameObject requested PlaySound Action with its AudioSource.
I saw from Unity Projects, they usually use Pooling even in Audio System. But still, they got a Monobehaviour and an AudioSource inside the pooled object.
Should i refactor my system? Or using AddComponent would be fast enough?
I generally either include the AudioSource within the pooled object or use separate (pooled) gameobjects dedicated to playing audio. Often the latter since lifetimes between audio and sources triggering audio differ.
yeah, these are gameobjects with my custom type called Entity
How can i accept Integer value only inside Generic Type like this: public class X<Num> : where Num : INumber I searched a little and found that it is possible with System.Numerics but it says its not implemented...
Where Num : int?
Or alternatively don't make it generic at all
If it can only be an integer
integer is not restrictive. However struct is but i want only integer. Hm youre right maybe i should use a field instead
You can also try unmanaged
But I think that also takes structs
But realistically you want your generic to only constrain because you are expecting it to have a set of methods / operations
Sometimes you don't need it to be all that constrained
Like vectors implement most operators, would you also want support for that xp?
Is there a point to disabling empty game objects if I am going to need them enabled afterwards?
That's pretty vague, it really depends on your usage
I pool the game objects and don't use them for some time, then afterwards put them to use
INumber and generic math was introduced in .NET 7. It's not available in Unity.
Disabling just makes unity ignore all the components attached to an object, so if they're empty, you don't have to disable them
If they have any components that require constant updating you'll want to disable them
Eg. If they have rigidbodies, colliders, or scripts with Update methods
So rigidbodies stop moving yes?
and lose velocity I hope
If the object is disabled? Yeah
Does anyone know if there's any solution to fixing the particle system? I've done a bunch of things to make it play, but it won't for some reason
I'm on 2019 BTW
Like I know it's not invisible. Setting it to automatically play works. It just has issues with playing through code.
Why can't we have the nice .NET features
Random.Shuffle
Once they finish the transition from Mono to CoreCLR, it will be easier for them to stay up to date with .NET. That transition won't happen until at least 2024.
OK nevermind. Particles hate switch statements apparently
The problems going to be your switch statement - the particle system has no knowledge of it, and isn't impacted from that any different than any other statements
The switch statement does everything fine; spawns an enemy, throw a debug message. It's just .Play() has a hard time with it
particle systems don't know or care about switch statements.
I'm trying to set up visual studio code, and I'm having trouble - I keep getting a million errors like "package x is in unsupported format (for example, a traditional .Net Framework project). It need be converted to new SDK style to work in C# Dev Kit." - does anyone know how to solve this?
not only that - I get no error messages. I just wrote AAA(); randomly in one of my functions, and I get no errors. That's weird
it's as if my intellicode didn't work at all - even though it supposedly should, I have everything installed
It did say that some features are disabled due to copilot, but does that include syntax highliting??
that makes no sense, hence why I'm asking
what's more, I save a file with a clear syntax error, and unity console just stays quiet about it... what could be wrong here?
I'm on linux btw, specifically endevourOs
it does find warnings - like a varaible that's never used - but random characters in-between functions or calls to nonexisting variables or functions seem to be invisible
looks like C# Dev Kit needs .Net 7 which Unity does not support
I open scripts by vscode, but get error, and There are no code hints! Error info: 2023-07-27 20:12:35.538 [warning] The project file '/home/Workspace/U3DTrain/Assembly-CSharp.csproj' is in unsupported format (for example, a traditional .Net Framework project). It need be converted to new SDK style to work in C# Dev Kit. 2023-07-27 20:12:35.698...
amazing what you can find when you Google
I've got everything working right now on my macbook -- vscode with the C# Dev Kit add-on, using the new instructions at https://code.visualstudio.com/docs/other/unity
It was not a painless process. VSCode decided it needed to re-download .NET on two separate flights where I had no internet access...
is it using .Net 7?
thanks, didn't find that somehow - but does it mean I have to go to the csproj file of every extension I have (70+) and edit that line there?
or is there an automated way to do it
It is. 7.0.10
It doesn't really matter what version of .NET the code editor is using. Unless you try to use a feature that Unity's .NET doesn't have, I guess.
problem seems to be in the .csproj files
I had a mangled csproj after setting this up
For some reason, every project was in there twice
even after regenerating external files
completely deleting it and then letting unity re-make it worked
hmm, problematical
once I followed the instructions properly, things have been working well
too well, sometimes
i really wish it would wait a moment before analyzing my code
There you go @wintry crescent , @heady iris is your goto man
leaving the Problems tab open as I type causes an amazing storm of error messages
I have an awful 2,500 line script file that takes just long enough to analyze for it to be pleasant
Is both the C# Dev Kit and C# package up to date if you've got them installed manually?
maybe everything just needs to be that large...
@heady iris Sorry bro to dump this on you, I dont do VS Code
ha, no problem :p
I installed them through visual studio code - they seem to be up to date
Are you following these instructions?
notably, you're going to be using the Visual Studio package, not the Visual Studio Code package
the most recent version of the former lets you pick VSCode as your external editor
I had to uninstall the "engineering" feature so that I could update the package. it was stuck on an older version.
I did follow them - It still doesn't work
Ah, that makes sense now, that will get round the .Net 7 requirement
I don't have the error messages now, so that's good - I switched to .net framework
but I still have no error detection inside vs code
I wrote
private void HandleInput()
{
_horizontal =
_vertical = Input.GetAxis("Vertical");
_rotation = Input.GetAxis("Rotation");
}
``` as a test - unity detects it as an error now, but vs code still doesn't
it's not an error
yeah that's valid syntax
That code would compile fine if the variables had been declared
assuming horizontal exists
The Dotnet had an update last days. Go to your settings in vs code, and set the "Use OmniSharp" = True . It reset on me so i needed to do that. Just try if it works
I have that unchecked.
Have a look in your Output windows. There may an interesting error there.
the "C#" one is not very interesting. It just says that it's starting up.
Dotnet path: /Users/crux/Library/Application Support/Code/User/globalStorage/ms-dotnettools.vscode-dotnet-runtime/.dotnet/7.0.10/dotnet
Activating C# + C# Dev Kit...
info: LanguageServerHost[0]
Starting server...
Anyone have a clue why my terrains are pink here?
private Terrain GenerateTerrain(Vector3 position) {
GameObject terrainObject = new GameObject("Terrain");
terrainObject.transform.position = position;
Terrain terrain = terrainObject.AddComponent<Terrain>();
terrain.terrainData = GenerateTerrainData(position);
TerrainCollider terrainCollider = terrainObject.AddComponent<TerrainCollider>();
terrainCollider.terrainData = terrain.terrainData;
return terrain;
}
private TerrainData GenerateTerrainData(Vector3 position) {
TerrainData terrainData = new TerrainData();
terrainData.heightmapResolution = terrainSize + 1;
terrainData.size = new Vector3(terrainSize, 10, terrainSize);
terrainData.SetHeights(0, 0, GenerateHeights(position));
terrainData.terrainLayers = terrainLayers;
// Create an alphamap based on the heights and apply the terrain layers
float[,,] alphamap = new float[terrainSize, terrainSize, terrainLayers.Length];
float[,] heights = terrainData.GetHeights(0, 0, terrainSize, terrainSize);
// Initialize alphamap to zeros
for (int i = 0; i < terrainSize; i++) {
for (int j = 0; j < terrainSize; j++) {
for (int layer = 0; layer < terrainLayers.Length; layer++) {
alphamap[i, j, layer] = 0;
}
}
}
for (int y = 0; y < terrainSize; y++) {
for (int x = 0; x < terrainSize; x++) {
float height = heights[y, x];
// Determine the layer based on height (modify as needed)
int layerIndex = 0;
if (height < 0.3f) layerIndex = 0; // First layer
else if (height < 0.6f) layerIndex = 1; // Second layer
else layerIndex = 2; // Third layer
// Check for index out of range
if (layerIndex < terrainLayers.Length) {
alphamap[x, y, layerIndex] = 1;
}
}
}
terrainData.SetAlphamaps(0, 0, alphamap);
return terrainData;
}```
Its because you are not using OmniSharp
pink terrain suggests that the material is broken
I do not remember where the terrain's material lives (in the TerrainData, or maybe elsewhere)
@heady iris So I need a base material for the terrain and then my alphamaps blend in new layers on top of it? So it's like a base layer all the others are painted on?
No, you just need a material for the terrain, full stop.
Inspect the generated Terrain component.
Okay, I will. Wonder if I can just use this: Material terrainMaterial = new Material(Shader.Find("Standard"));
okay
i'm using something custom here, making unity yell at me
the shader name will vary based on your render pipeline
I've never actually created a terrain component through code before. I wouldn't be surprised if it wound up without a material assigned to it.
Okay great, I think this is progress ๐
Whenever you see that weird pink color, it means a shader isn't working
or that there's just no material assigned at all
I created a terrain in the editor and this was the default material:
But TerrainLit isn't returned by Find.
terrainMaterial = new Material(Shader.Find("TerrainLit"));
This is looking for a Shader named "TerrainLit" and trying to create a new Material Instance with that Shader
You could Serialize the Material in the Inspector or you could put it into the Resources Folder and use Resources.Load
If you check the Material itself in the Inspector, there's a Drop-down at the top which shows you the name of the actual Shader used by that Material, if you want to know which one it is
Are you missing a Rigidbody2D or forgot to set the Collider to isTrigger?
It's probably not a coding error but instead something with the composition of your GameObjects
You could show screenshots of the Spawner and Terrain Inspectors
terrainMaterial = Resources.Load<Material>("Materials/TerrainLit");
That doesn't appear to be the correct way to load a material. Anyone know what I'm doing wrong?
GameObject.Find?
Assuming that Materials directory is in Resources directory, it should work.๐ค
terrainMaterial = GameObject.Find("demoterrain").GetComponent<Terrain>().materialTemplate;
Lol, I added a terrain object to the scene and did this. So it works, I just need to find the correct location of hte material ๐
Guys. I have two character controllers. At every frame, I change the character controller radius and height based on a few values. Both characters collides with each other normally, but sometimes, when their radius or height changes, they don't collide anymore, and pass thru each other. Could that be the reason for them not colliding anymore?
I think there could be an intersection between those when you change their radius/height which may lead to not properly receiving a collision, but I'm not sure
I think this applies to Rigidbodies as well, sometimes
Could using a Rigidbody-based CharacterController handle these?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
can't tell without first looking how you move characters inthe first place
^ code would be helpful
Possibly, or you could do something towards Physics.CheckBox or whatever when you're changing the Radius/Height to check for a potentially ignored collision by yourself
Does CharacterController have something similar to the Rigidbodies CollisionDetectionMode?
where is movement? this script is a mess
I have a list<A> and a list<B>. They contain 4 instances of A and 4 instances of B.
I want to do something like a cartesian product but rather than test values individually, I want to test every configuration of the whole thing.
e.g. 1x 2y 3z 4w = 1 configuration. 1x, 2y, 3w, 4z = 2nd configuration, and so on.
Any idea how I can achieve this?
https://github.com/rickomax/Acknex/blob/722c5def53c4cec971de8cb25ef01ac57429ab13/Assets/Scripts/Acknex/Objects/Actor.cs#L40
This is a coroutine that all the other moveable objects beside the player uses to move
If one day you understand what the project is doing, you might know why it "looks like a mess"
It is a raycaster engine port, and the original engine itself is a mess
But the movement is right there CharacterController.Move
yeah it just takes lots of digging
I think it's fine, not toooo messy, but you could definitely extract out a loooot, for example a wrapper around retrieving and updating from the World.instance
putting everything in one script is difficult to debug
the movemnt code at least is using physics so that can be crossed out as culprit
Yes, definitely, and it's a lot of unnecessary responsibility in there, but overall it's clearly understandable I'd say
All these World.Instance things are updating values the game scripting engine uses
And reading from these values as well
So the game script can change variables that modifies players and objects positions as well, but it is not doing that when the physics breaks
Game script are not ordinal C# scripts, they are C# scripts I transpile from the original game scripting language
Does anyone know? ๐ฆ
@wild bane
I'm still reading through the code, but just asking, are you doing more then 1 call of Move on the CC per frame? Are you eventually setting transform.position on it somewhere?
Definitely only a single Move per frame, seemingly
I don't do more than one Move per frame, but yes, I set transform.position, lemme find where
show canvas inspector
You can't draw line renderers in screen space afaik.
And canvases always render last.
So there's not much you can do.
which part of inspector?
the whole canvas object
https://github.com/rickomax/Acknex/blob/722c5def53c4cec971de8cb25ef01ac57429ab13/Assets/Scripts/Acknex/Objects/Player.cs#L85C43-L85C52
Keep in mind all these reading and writing to World values is to keep the character sync with any script changes from the original transpiled scripts
oh ok ScreenSpace - Camera Should respect sorting
but the line drawing is not done in the canvas
But you want it to draw on top of the canvas, right?
opposite
no, the problem is the line is drawn on top
Oh
CharacterController.transform.position = initialPosition;```
Inside your `UpdateObject`
Idk if that may be an issue, could you apply those within your CC `.Move()` instead?
Why does it receive an initial position every frame?
all the buttons are the canvas and the yellow and grey line are the linerenderer stuff
\
did u check this
on line renderer
Yes, but I see that the real problem occurs when the CharacterControllers (things and player ones) radius changes
whats order in layer set to
make it higher than canvas
Can you not use screen space - overlay canvas?
If my TerrainLit material is here, why isn't this loading it? terrainMaterial = Resources.Load<Material>("Materials/TerrainLit");
so if canvas is order in layer of 1, make the order in layer on line render > 1
like2 or 3
should work since you have screen space - camera
There is enableOverlapRecovery for CC, but Docs write that it's only for static object overlaps
Maybe skinWidth?
no nothing sorting layer
Lines use the drawingLines layer and the menu uses the BottomMenu layer
So maybe I need some custom depenetration code?
layer 0 means is at the bottom
no because it destroys other stuff
afaik
if you want drawing line ontop then I think you need to put as index 4
where bottom menu is
That would definitely be an option, but idk if it's the "best" one, sadly I've always used Rigidbody controllers so far
I've tried everything, even putting them in the same layer and nothing works
I've tried that @rigid island
As far as I know, changing collider radius based on mesh bounds or things like that is kinda normal. Not sure if that is "safe", tho
Lemme try locking their radius
oh sorry you want line renderer behind right?
switch the order
@stark sinew , by locking their radius, the problem does not happen anymore :/
And their radius can change very quickly because they're based on a sprite radius (relative to camera)
not working.....
not sure why, it should..
maybe someone in #๐ฒโui-ux knows , this isn't code related so far ๐
Can you pause in Playmode, then go frame by frame, and check what happens at that exact moment in the scene?
Do the CC bounds look as expected?
Do they suddenly overlap each other?
Hi - I keep having those problems with my linux visual studio code install. I tried basically all of the things that were previously mentioned - including replacing some text in all csproj files from <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
to
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<TargetFramework>net7.0</TargetFramework>
which gets immediately reverted anyway whenever I try to open vscode from unity
and even when it's changed after vscode was openend, I still have no autocomplete
I tried everything, from switching to .Net Standard 2.1 or back to Framework 4.7.1, recreating all project files, messing around in vscode extension settings, I don't know what to do anymore
hello, i came from web development, and there's one thing is missing for me, its DI container, for example how can i organize acces to player script from another script on any object, by not adding player field to the another class or using "GameObject.FindObjectsOfType"
@stark sinew
by making the class/ method static, then you can access it by Class name rather than by reference
ahhh forgot u said u changed the Z as well
@stark sinew the radius grows too much and too fast, I guess, so the collision will break. I can't even interpolate that bc the change could happen at every frame. The best I could do is trying depenetrating them manually
i kept all mine on 0 @hexed ingot
Dependency injection is not magic. Learn how it works wherever you're used to use it and implement it in similar way in C#.
Or you might want to use some existing dependency injection libraries/assets.
thanks
thanks
well, this was kinda a stupid mistake - the trees I referenced were Unity Terrain Trees and not my custom tree class...
hi there, i want to make a 2d top down game about automation with elements similar to factorio, how would i go about making the conveyor system? do i move the items using physics and effectors or do i make a custom system were i move the items every tick on the next conveyor? i already have a grid system
Thanks @stark sinew
Do not cross post
what do you mean?
why do I not get any coloured code compared to the tutorial
!ide
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.
ok sorry
hello my rigidbody velocity going down. How can i stop it in the zero?
i am trying to rotate a gameobject in update
newRot = steerInput * turnSpeed * Time.deltaTime * moveInput;
transform.Rotate(0, newRot, 0, Space.World);
but it runs smooth when i have 800 fps but in 60 fps it dont rotate much
so i tried to put the 1st line in update and second in fixed update then its rotating in 60 but not in 800fps
do anyone know why its happening
Hi, I'm trying to use the profiler for the first time to investigate a performance problem. I'm not sure where to go from here, but this seems abnormal to me.