#archived-code-general
1 messages · Page 181 of 1
i mean that it kept instantiating the obj and adding numbers every second until the game crashed
when i used that if statement
whats the z of your object
well it is 0
ah
well it loops infinitely bc you didnt add back the check that count is false
that if just covers distance to the point
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CameraFollow : MonoBehaviour
{
private Slider cameradistance;
public Transform target;
Quaternion toRotateBy = Quaternion.identity;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
toRotateBy.eulerAngles = new Vector3(70, 0, 0);
transform.position = toRotateBy * Vector3.forward * -(cameradistance.value) + target.position;
transform.LookAt(target);
}
}`
im not getting errors anymore
but
its not following my player anymore
ok the if statement works now however the points value is not changing
also, if youre at all worried about v3 distance you can do
Vector2 pos = new Vector2(transform.position.x, transform.position.y);
float dist = Vector2.Distance(pos, target)
if (dist < whatever...
points didnt increase by 1?
In the if statement I have
points = points + 1;
score.text = points.ToString();
Basically I want the text to change up 1 number everytime a new obj is instantiated
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ProductMoving : MonoBehaviour
{
private float speed = 0.2f;
private Vector2 target;
public GameObject thisPaper;
public TMP_Text score;
private GameObject newPaper;
private bool count = false;
private int points = 0;
void Start()
{
target = new Vector2(-0.542f, -0.33f);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target) < 0.1f && count.Equals(false))
{
count = true;
points = points + 1;
score.text = points.ToString();
newPaper = Instantiate(thisPaper);
newPaper.transform.position = new Vector2(0.007f, -0.042f);
}
}
}
it is very scuffed as i put it together at 2AM 😆
ohh its the count aint it
its to make private vars accessible in unity editor without making em public vars
so you have the object move towards its target and increase points by one, and then it doesnt do anything else
I see thank you very much
Basically its a 2D factory belt type system. An object moves down the belt and when it gets to the bottom (target), it stops. A new obj is instantiated and moved back to the top of the belt and the process happens again
i want to add +1 to point as soon as a obj hits target
is it the most preferred than the other methods?
depends on if you want your variable exposed to other scripts or just the editor
Is there any way to call "remove" on a slot that you destroyed the object from in a list?
Since normally you remove with the gameobject, how can I remove its index?
so the points say 0 in the label and when the initial obj hits target, it changes to 1 but when any of the instantiated ones hit target, that value doesnt change @harsh bobcat
RemoveAt
Could I get help with #1145208770327232543, tldr is the title
oooo danke
my guess is your instantiated target has its variables set incorrectly. try setting count to false in start
Okay so I thought I was having a different issue but after reading a bit I'm still confused about how to deal with this error:
well count is created in the start of the script as private bool count = false;
wait @buoyant zenith what i said is completely wrong
so its that points for every item starts 0
you add one and then set text
make points static like public static int points so that every object shares that variable
OH RIGHT
im curious how to do the getcomponent method
GetComponent<>();
I have a list trashinPlay that exists on a ScriptableObject that I add the scene's objects to when they spawn, however I want to currently delete all the saved objects from all the scriptableObject files, and when I try to loop through and delete all the TrashObjects within the trashInPlay variable on the ScriptableObject, I keep getting an error that the list doesn't exist?
I'm running it in OnDestroy, which is what I kept asking would run and still have access to the scene during exit, which it is supposed to
private void OnDestroy()
{
for (int i = 0; i < trashTypes.Count; i++)
{
for (int j = 0; j < trashTypes[i].trashInPlay.Count; j++)
{
if (trashTypes[i].trashInPlay[i].gameObject != null)
{
Destroy(trashTypes[i].trashInPlay[j].gameObject);
}
trashTypes[i].trashInPlay.RemoveAt(j);
}
}
}```
Not certain, but it might be because you are iterating forwards while removing. Have you tried iterating backwards?
Yeah that's also an issue - removing things from the list while iterating over it is going to cause issues
let me see if that's i
i remember RemoveAt(idx) will move all elements after idx forwards so that shouldnt be issue
but you may miss to destroy some elements
you need to iterate backward
it will definitely be an issue yes, you will miss things
I have a game with some UI layer stuff and some world stuff. If I want to capture input in UI, I've traditionally done it by overriding the interfaces IPointerDownHandler, IPointerUpHandler, etc. I'm not familiar with how best to do this in world space so that it doesn't conflict with the UI layer captures. Lots of googling shows that people use Update() checking. Is there a better way?
Should I be posting my TTF font material question in dots or here?
Hello all. Any method to execute Update method when my iPhone or Android turn to background mode?
i believe your update still works in background but at different fps
Unfortunately, It doesn't work when I press hold button on my iPhone
Update Method has stopped
I already set about background.
But It doesn't work and I hope this is the configuration what you said
ok for phones its a different story
I have a GameObject that has both DDOL and LevelManager scripts.
public class DDOL : MonoBehaviour
{
private void Awake()
{
if (GameObject.FindGameObjectsWithTag("ScriptsHolder").Length > 1)
Destroy(gameObject);
else
DontDestroyOnLoad(gameObject);
}
}
In LevelManager I assign an instance to the script in Awake.
private void Awake()
{
instance = this;
// ...
}
Because of Destroying my GameObject in DDOL script it throws me this error:
MissingReferenceException: The object of type 'LevelManager' has been destroyed but you are still trying to access it.
I am very poor in working with instances and ddols, is there any possible solution for this issue?
So, I must implement service to resolve my issue. right? There is no solution in just Unity.
well thats what google told me, you can try searching other answers but apparently "Unity runs as Activity in Android, hence it gets paused when it's loses it's focus. That's by (Android) Design and works as intended."
Yeah, I also saw it, This is the other word to say there is no solution in unity own.
why is it so neccessary for u to run in background?
I must play some audio repeatedly with some intervals.
i think there is some notification system
that u could use, im not 100% tho
notification system?? more details?
I think this is about push notification
So recently I found out about the "Root motion" command in the animator but when I enable it it messes up all my animations. I need to enable it because one of the problems I have been getting is being fixed by the use of root motion. There's an animation if I press the "W" button it plays a certain animation on the camera where it goes forward then turns left. With root animation on it does the animation but the camera just rotates and doesn't move its position unless I hold the "W" button. Even then when I let it off it snaps back into its previous location
Does anybody know how to fix itch.io scaling? When i have the game imbedded the game is just cut off, i want it to rescale to the size of the screen, help. https://bore1.itch.io/myskvllmedgubbish?secret=1Xlhz5459jqbt2ON013GXhSEr4
Could I get help with #1145208770327232543, tldr is the title
How can this error be thrown if my script is definitely in the scene?
MissingReferenceException: The object of type 'LevelManager' has been destroyed but you are still trying to access it.
looks like the LevelManager you are referencing has been destroyed
you'd have to show code / explain what's going on if you want more help
also show the rest of the error message
yes, but why does the script get the LevelManager that is destroyed, not that is in the scene?
How shjould i know
this.
You haven't even shown what line the error is on
should Unity get the script that exists.
nor explained which script is on which object
in which scene
we don't have enough information to help you
on the line where I reffer to the instance
which is what?
SHow the full error message and the full scripts
and explain which objects in which scenes have which scripts on them
Don't make this a game of hide and seek. Just show us the details
this is full error https://www.nombin.dev/pqjhapvpyg
Ok so show the LevelManager script now
GameObject #ScriptsHolder has both LevelManager and DDOL scripts
and show where and how you set up whatever UI button is invoking this thing
modifyLevelButton.onClick.AddListener(() => ModifyLevel());
private void ModifyLevel() =>
LevelManager.instance.LoadLevelCreator(levelsSelectionField.currOption.GetComponent<LevelInfo>().levelData.id);
^
just various methods
https://www.nombin.dev/kiijinlkog
that code doesn't match with the error you showed
The error says:
LevelManager.LoadSceneAndLevelData (System.String sceneName, System.String levelId) (at Assets/#Scripts/Managers/LevelManager.cs:155)
implying line 155 would be inside a function called LoadSceneAndLevelData
You have asked me to show LevelManager script
but the script you just shared has line 155 in the GetAllLevelIds function
it means you changed the script since you got the error
please get the error and don't change the script between sharing the error message and the code
oh, you are right, I deleted what I have commented
you can be sure that no behaviour was changed
right but now I don't know where the error is happening
because I can't match line numbers in the error up to the script
I see, that's another error:
https://www.nombin.dev/ogjleocwkg
now everything matches
In LevelManager I assign an instance to the script in Awake.
private void Awake()
{
instance = this;
// ...
}```
your problem is that you are doing this regardless of whether this particular LevelManager instance is going to survive or not
so:
- you load a new scene
instance = this;runs on the new LevelManager in Awake- The DDOL script destroys the new LevelManager (and itself)
and now your instance variable is pointing at the destroyed LevelManager instead of the good one
but there should be another instances?
so>?
It doesn't matter if there's an instance
your instance variable is pointing at the destroyed one
FOllow established singleton patterns
why would oyu make it null
I have found none.
you haven't looked very hard then
you tried to do this cute thing with having a single DDOL script manage all the singletons
it's backfiring on you
just do it the normal way
oh, I was trying to find DDOL patterns
so I will have to write own ddol logic for all scripts that want to be ddol and have an instance?
Many of those implementations provide a simple base class to inherit from
and idk what you mean by implement your own logic
the patterns are there to be copied
I mean I have to make a GameObject DDOL without adding a DDOL script on it? Instead I have to write this logic in the script that is attached to it
for every GameObject.
The singleton script itself will make it DDOL
I see, well, I will try that. Thank you for your help 😄
the separate DDOL script is not helpful\
foillow the established patterns that are all over the place
looks like I have to stop overthinking
got a question:
why when i rotate around the z axis a 2d object while i move, the movement is jerky
like laggy
probably due to your code
we can't help you without knowing more
i will send it rn
The movement code:
horizontal = InputSystem.GetHorizontal();
vertical = InputSystem.GetVertical();
Vector3 direction = new Vector3(horizontal, vertical).normalized;
rb.velocity = direction * speed;
The player rotating by the mouse cursor (looking at it):
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 watchDirection = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y).normalized;
transform.up = Vector2.Lerp(transform.up, watchDirection, rotationSpeed * Time.deltaTime);
you showed the same code snippet twice?
IM dumb
done, im sorry, i forgor to copy
modifying the Transform directly when doing RIgidbody motion is always going to be weird/jerky/buggy
why is that
because you're fighting against the Rigidbody
which wants to control the object's motion
oh shoot
urgh
i forgor now that i froze the Z rotation....
i think this is a problem, am i right
ye, you're right
as a matter of fact, how should i manipulate it then and keep it smooth and also keep the rb
Is there a way to tell child objects of a parent not to react with opposite force when you move the parent with AddForce()?
No
you can unparent them, and then parent again
they shouldn't be reacting with opposite force 🤔
do the child objects happen to have their own rigidbodies?
i believe he wants only parent to be moved with the force
and not children
Yeah, it's rigidbodies under rigidbodies, which I'm starting to see is just really screwing a lot of things up lol
In this video, going up and down moves the socket (the part between the bars and the arms), but moving up and down flings the arms with the "opposing force"
don't make a dynamic rigidbody the child of another dynamic rigidbody if you want them to move together
you could try forcing their velocity to 0 right after u do the push though
I've tried many versions of that and not been able to get it to work, and the velocity can't be 0 because they're supposed to be actively seeking the rotation of the red ones
velocity and angular velocity are 2 different things
They have fixed joints though, how would modifying the velocity of something that's being flung by its joint to rotate going to affect that 
I can try it, I've just tried resetting velocity on other objects and it consistently wouldn't work lol
nah, doesn't work :p
I think I just like
Wait
can rb components be enabled and disabled at runtime?
yes
solved it, made 2 objects, the player with the player script and rigidbody, and the player object with the sprite and collider, works flawlessly now, thanks 💟
but if ur parent moves ur object will move with the parent thats the thing
so idk if anything except unparenting will work for you
you could try saving world position of each children and force them to stay there after the push
no, rigidbody does not inherit from Behaviour so it does not have an enabled property. you can make it kinematic though if you don't want it to be affected by forces
true, my bad
How would I clamp these values on input? I'm running into an issue where the player's right stick (moves reticle) is clamped to the screen bounds but their input can keep updating and increasing in value.
Vector2 aim = playerInputActions.crosshair.aim.ReadValue<Vector2>();
you'd clamp the reticle position, not the input data
Hey, i have this function which translates the suspension of my bike front wheel perfectly - but if my bike rotates 90 degrees on any axis the front wheel is flying away
Maybe someone have a good idea? ❤️
private void SuspensionVisualUpdate(Transform transform)
{
if (!Grounded())
{
_wheelFrontSuspension.localPosition = Vector3.Lerp(_wheelFrontSuspension.localPosition, _wheelFrontSuspensionStartLocal, 0.05f);
_wheelBackAngle.localPosition = Vector3.Lerp(_wheelBackAngle.localPosition, _wheelBackAngleStartLocal, 0.05f);
return;
}
_wheelColliders[1].GetWorldPose(out var posBack, out var _);
_wheelBackAngle.position = posBack;
_wheelColliders[0].GetWorldPose(out var posFront, out var _);
var distance = posFront.y - _wheelFrontSuspension.position.y;
_wheelFrontSuspension.Translate(new Vector3(0, distance, 0), Space.Self);
}
So I believe I've done that as the reticle doesn't move past the screen. But the reticle's position does take the player's input of the right stick into account. So the input thinks the reticle is off screen and to bring it back I have to hold it equal to the amount that I held it past screen just to get the reticle to move the opposite direction.
well that wouldn't have to do with the code you shared above neceessarily - since that's just the stick input right?
you'd have to show your code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Lines 55 and 57 are currently clamping the positions
you're not clamping this aimOffset variable
which seems it can freely go off screen etc
what's the relationship between targetPosition and aimOffset
what are they used for
and why are they different variables?
all you need is Mathf.Clamp your local rotation of the gun for example in min and max values you want
Uh hrm. So I used to have these lines
// Apply the aim offset to the local position
targetPosition.x += aimOffset.x;
targetPosition.y += aimOffset.y;
I'm using an object in the world which is where target position comes from. And I have a sprite (the reticle) on the GUI that follows the object
So there are some conversions happening
The aimOffset is the data from the player input, the delta time, and the speed. That gets applied to the target position and then I convert that to the desired position and move the target there
xGunRotation = Mathf.Clamp(xGunRotation, -90, 90); and then use that transform.localRotation = Quaternion.Euler(xGunRotation, 0f, 0f);
https://gdl.space/rijufayoya.cpp
I had a procedural recoil animation script that was originally attached to the GunHolder, which is the parent of all the guns in the game. meaning, that every gun would have the same amount of recoil. I changed that and have been left with some weird results that idk how to fix
its gonna make sure your rotation doesnt go above or below limits, and than use that value that is already for sure not going over or below limits whereever u want
I'm not rotating the character though
you are rotating something
messing with the settings doesnt help
I'm not
I'm moving something left and right and up and down
think of it like a gallery shooter
oooh i though u had different issue my bad
like Duck Hunt
no worries, I appreciate the insight though
Clamping the aimOffset sounds right to me
I can try that
can maybe someone help with that? 🙏
That did it! There are some other funky stuff going on, but I can sort through that
Hi. One question, is there a way to like reference a custom folder in the built game folder please? Like for example to be able to add 3D models externally or json files please
like get what's in that folder I mean
@rough sorrelhttps://docs.unity3d.com/ScriptReference/AssetDatabase.html
take a look at this
but like where would I have to create the folder in the exported game files please?
how do i use this to do more than one thing with out making a function, or do i have to make a function if i want it to do more than one thing?
myInputActionsGet.Player.Interact.performed += ctx => Debug.Log("Do this"), Debug.Log("And Do this")
use a statement lambda instead of an expression
oh coo you can
yes, but it will probably be better to just use a method so you can also unsubscribe from the event
otherwise you have to store the lambda in a delegate field so that you can subscribe the delegate to the event and be able to unsubscribe it
Oh shoo your right.
Whats a better way to
myInputActionsGet.Player.Interact.performed += ctx =>
{
hit.transform.SetParent(spawnAndHoldPosition);
hit.transform.position = spawnAndHoldPosition.position;
};
Is there a different way to use the player Input system?
use a method instead of a lambda
that would allow you to unsubscribe like i said before
every time i pick up i need to subscribe, when when put down i need to unsubscribe the input performed?
well if that hit is a local variable, then absolutely
if it is a field, then you just need to subscribe one time instead of every time you pick up an object. and you'll only need to unsubscribe when you want to stop reacting to the event
Dose that mean right after "pick up" += I can -= since its picked up I don't need to use it anymore until the next time I "pick up". or am I over micromanaging?
This is a programing channel, you might want to try https://discord.com/channels/489222168727519232/532311577576210432
Alsto you can click and drag object into the game engine or into your scene.
it sounds like you are designing this in a super weird/complicated way. show the full context if you want a suggestion on how it can be improved
this is still a programming channel, mate
Q: Why would my ViewportToWorldPoint clamping only restrict half the Y axis?
https://hastebin.com/share/nufamuvexu.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The X axis clamping works perfectly fine
But here, the reticle can only traverse in the red box area for some reason
not the whole viewport
Hello guys ! If I want to procedurally generate chuncks of a gridded map let's say, is it better if I use prefabs of a typical map square, or instead I use premade scenes, with the sub scene tech ?
That depends a lot on what the content of a grid is and the size of everything. It might be fine to cram it all in, lazy load it as prefabs, bring it in as asset Bundles, or additive scene load.
It depends on what you want to do. You can unsubscribe if you don't want to listen. There are benefits either way imo
is there a way to find the gameobject with a specific script attached to it?
But subscribing and unsubscribing seems more likely to introduce bugs to me
FindObjectOfType or FindObjectsOfType just be aware it is not that performant
I.e. using it an Awake isn't so bad, but in an Update would be not ideal
oh. I mean in the editor
In the search field, type T:<script>
And it'll show you only objects with that component on it.
does the record keyword work properly in this version of unity's C#?
I tried a bit a while ago, to no avail, but idk if I was just doing it wrong
https://docs.unity3d.com/Manual/CSharpCompiler.html
Record support
C# 9 init and record support comes with a few caveats.
ty
record you can use, but not record struct 😞
Wonder what are the "caveats" they're talking about, I mean records are just compiler trickery and expanded into a class/struct that implements IEquatable and stuff. Maybe because of the yet other caveat of the init properties
it's the init thing and unity's serialization not supporting them
They are likely talking about you having to define IsExternalInit
Ah yeah it indeeds creates init-only properties when adding stuff in the primary constructor
They'll have to do it at some point™️ when switching to the core CLR anyway
Bump 🙂
god the switch to core clr can't come soon enough at this point. they've already said that when the switch does happen that it'll be on the latest .net version
full record support, including record structs, with expressions for normal structs, generic math, static interface members including operator overloads. so many useful features
Would be nice if they finally fixed the naming conventions (=> this.Transform.Forward) at the same time but that would break everyone's code lmao. Maybe design a code fixer like they did when they obsoleted [GameObject].collider and others in favor of GetComponent
That sounds like never gonna happen
agreed, someone suggested going through and updating the naming and removing all of the obsolete members from super old versions in the future of unity and .net forum thread, but they shot it down iirc
Yeah it would be a huge task, basically going over all exposed types to rework them
Meh nothing a good search & replace with an elaborate regex can't do
Think they would be too worried for backward compatibility
And breaking reflections, etc
Oh yeah there's the C++ bindings too that would need some updates
But yes at least removing the things marked as obsolete since 10 years would be nice
honestly all this backwards compatibility nonsense from super legacy versions should be thrown out. let's get some breaking changes that make using the engine nicer
I imagine it's planned as the new ECS systems come online and mature, but the amount of stuff thrown out might be larger than expected 
For a brief moment we had it with Unity Tiny 😛
Whats a common way of running a visual lerp when you wanna start it from something outside of Update? Coroutine?
I think so
I managed to figure it out after trying to wrap my brain around it for over an hour, decided to make a method shortening the process that also makes it more intuitive, I just plug in a transform and a Vector2 and it returns a localized Vector2
Use DOTween
trying to build for android, any idea on these daemon errors?
Click and see error details
its possible you have an invalidpath/special characters in your filename that it doesn't like
oh it says use --status to get details
Any chances you are trying to attach debugger to the project?
You cannot use Script Debugging for Android. Weird things happen. You can use Autoconnect Profiler to identify keypoints that could be causing your game to lose performance.
in a cmd terminal?
uhhhhhhh
i dont think so
I would first clean your temp folder and create a clean build.
temp or tmp
The temp I'm referring to is the cache folder inside projects/library folder.
i tried deleting my library and .gradle folders
the erros seem to have changed slightly
but not much
the library folder inside this specific project or the projects folder
Have you tried including the symbols.zip? It's in this image here just enable it.
ill try
public or debuggin
debug
ok
Do you have any editor scripts?
I have a c# script
Yes I understand. I'm asking do you have any editor scripts?
I am sorry but I dont know what an editor script is
I googled it, nope
none that I am aware of
Kk, do you have everything set up with Android studio?
so i have android studio installed but I dont know how to connect it to unity. I have android support installed with my instillation of 2022.3.8.f1
In order to build to Android everything needs to be set up with studio.
It's not difficult but too deep to explain over discord.
ah ok
do you have any reccomended tutorials?
It's really not difficult, should take you 30 min.
also, i forgot to mention but I am not sure if openjdk is installed
i got it set up in in system variables but java -version only shows runtime
If I remember correctly the install should handle all envs.
You just install through android studio.
I wouldn't reccomend the non studio way for a beginner.
oh
the manual said i had to install jdk
That's handled in both unity hub and Android studio.
I'm 90% sure.
Last time I have done it.
You can install JDK through Unity Hub, but I've heard problem installing it in the past regarding which version to install and make Unity work with it.
do i need to install any plug ins inside of android studio?
installed apparently
There should be a sdk and something else.
NDK
^
an ndk plug in in studio?
Both yes
Google.
ok
I'd suggest reading and understanding the error first.
Something you were told to do a long time ago:
#archived-code-general message
how can i remove the text from the button
You delete it from the Hierarchy
no like , i delete only the text not the whole thing
cause im following breckeys tutorials on TD and idk how he removed the button text
you can find the component that has the text on it and delete the text component (right click, remove component), or alternatively set the text to ""
"TextMeshPro - Text" is the component on this image that has text functionality
doesnt have one seems like it
then it's underneath it in the hierarchy - unfold "ShopTurretItem"
Look at the hierarchy.
This is really beginner level question and not even code related.
ooohhh
Has anyone ran into an issue with the new Input System and having objects or players keep moving after the input is released/let go?
sorry , didnt know where to ask
You should go through the beginner pathways on unity learn.
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Sounds like a logic issue in your code.
Absolutely. I can't pin point it though.
https://hastebin.com/share/elekuzoyiy.csharp
Line 20 is where I read the input
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It seems like I never reset the amont of aim offset applied to the object
Would I do that by setting the aimOffset to 0 after I move the object?
LETS GOOOOOOO
this fixed it
it diddly done works
hrm. looks like that fixed it.
for some reason running the game in the editor doesnt work, only building it does
but that is a separate issue
anyone know how to run asynchronous code? What I have here doesn't work—I get the error "BuildNavMeshAsync can only be called from the main thread."
public async override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("Generate Navmesh"))
{
NavMeshBuilder.ClearAllNavMeshes();
await Task.Run(() => NavMeshBuilder.BuildNavMeshAsync());
Debug.Log("Navmesh Successfully baked!");
}
}
I'm destroying a lot of gameobjects at once, but It doesn't seem to be destroying all of them? You can see in the deubg log:
Destroyed by Walk 12,1
which is called right after destroying it.
for (int i = 0; i < maxSize.x; i++)
{
for (int j = 0; j < maxSize.y; j++)
{
if (rooms[i, j] != null && rooms[i, j].walkValue == 0)
{
Object.Destroy(rooms[i, j]);
Debug.Log($"Destroyed By Walk: {rooms[i, j]}");
}
if (slow)
yield return null;
}
}
Task.Run launches a separate thread. Just await the method call
it doesn't look like BuildNavMeshAsync is awaitable though
this is the error I get for that
async await is what I'm used to coming from Javascript
looks like you'll have to use NavMeshBuilder.isRunning
What is rooms
an array of TestRooms
You are deleting component not game object then
why does it work for the others then
because that whole space is covered in blue cubes at the start
Idk, something else is deleting your GO
i mean the blue cube SHOULD dissapear
the blue cube is drawn with a gizmo via TestRoom
so just destroying TestRoom should destroy it
however I think i found the problem, i think it's actually adding duplicates somehow
K then your array does not contain all of them or your condition is wrong
yea, I think it's somehow spawning multiple with only adding 1 to the array
try this:
NavMeshBuilder.BuildNavMeshAsync();
while (NavMeshBuilder.isRunning) {
await Task.Yield();
}
thanks
I'm unfamiliar what Task.Yield() does though
Might want to read through C# manual on async await(and potentially other things), since it's probably different from JavaScript.
And then through unity manual on "await support" as it is also a bit different from plain C#.
the only time I used async await in C# was Task.Delay(seconds)
specifically with unity's synchronization context, Task.Yield basically just delays one frame
huh, it works perfectly
I was in the middle of implementing a crazy complicated solution on SO about running it on the main thread and all
It probably is running on the main thread though. Just asynchronously.
Though there might be jobs involved as well.
you can use either but Task.Delay is a bit more heavyweight (allocates memory etc), it's similar to the difference between yield return null vs yield return new WaitForSeconds...
I simply found it easier to read/implement than coroutines
though I didn't know there was a difference in performance
i don't think coroutines and async are drastically different in terms of performance but there's ways to shoot yourself in the foot either way, if you're doing something in a loop every frame you probably want to use the methods that don't allocate anything
Hey sorry I know this is a physics Q but no one ever replies in that thread.
I have weird coordinates for Z position on a prefab I put into my scene, and I don't understand why. All other objects have regular Z position of 0, but if I change the Z coordinate to anything other than this exponent then it disappears
Open the prefab and look at the child position.
Also, probably better move to #💻┃unity-talk
I will move it over there, thanks. I did change the child position of it to 0 0 0
but it was those coordinates originally
When unloading scenes, are static classes also destroyed?
Because it would appear so. And if so, how to stop being from being destroyed
Can you be way more specific about what you mean by "static class"? Because that has a very specific meaning in C# and or conflicts with the idea of even having something to destroy. Static classes cannot be instantiated
So you're just talking about a component that you happen to have a static reference to
This class creates an audio source in the current scene and uses said audio source to play ui sounds
You should look up DDOL singletons.
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
no no, thats not it
Right it's an object in the current scene. It's not a "static class"
wait
I have 2 scenes,
Scene A and Scene B
I load Scene B,
When Scene B is fully loaded, it calls a method in said class which creates audio source and stores reference to it
when scene B is fully loaded, I then unload scene A
Scene A does not reference said static class or audio source in anyways
how ever when I unload it, the static class audio source reference becomes null....why?
because every object in the scene is destroyed when the scene is destroyed
the audio sources is still* active in scene B, said audio source is still there, but for some reason the static class lost reference to the audio source
How are you verifying:
- that the object is created in scene B.
- that the reference becomes null?
it is a method in SCENE B, that creates the audio source,
at no point does Scene A reference said audio source
what does "method in scene b" mean exactly
Can you answer these? #archived-code-general message
sure but this doesn't really tell us that much
show the hierarchy before and after the audio obejct is created
show us where the object was created
and then show the hierarchy after scene a is unloaded
note that there are certain rules governing which scene a GameObject is created in when you run new GameObject (it's the "active scene", which has a very specific meaning).
ahh
The active scene can very easily not be the same scene that your script with the Start method there is part of
I assume you're seeing some error or something
that you are trying to explain?
Mind sharing that error with the rest of us?
So this is the OBJECT before audio source
sec
audio source is still there
strangely, everything worked now...
the reference didnt turn to null
ima run again wtf
sigh
its working
wtf
i swear, 15 minutes a go, this shit wasnt working
wait, nvm, changed something 🙂
so the audio source is still there"
but the audio source reference is null
@leaden ice it only becomes null after the SCENE A gets unloaded,
Well, ive verified if the class is being reset and its not
so the reference is just being lost somehow...
I just verified, and yes, it was being created in this scene, guessing the reference was cleaned up, but the component stayed in the current scene 🙂 Thanks
I want to make it so i can increase the kill count when an enemy dies, but if i did it through my enemyspawner it requires the prefab of the enemy. is there any way i can make it so i can access my controller without having to use it as a serializefield?
the one problem was that the controller was attached to the camera, a child of my player and it gets a type mismatch when i try to put it on the enemy prefab
Your enemy shouldnt be responsible for increasing the kills.
One solution could be just use an event on the enemy, invoke it when dead. Anything that cares about enemies dying will subscribe to it
is there a way to check onDestroy for a specific prefab?
Literally what I suggested..
you could just pass the controller / counter script on instantiation of enemy
then increase when dead and destroy
Look up what events are
are you guys using Visual Studio Code?
I love vs code it's just too much of a hassle to work with for some reason so I just use good ol' vs
No, Rider.
is there a way to check if an instantiated object has been destroyed?
it just suddenly stopped working on me yesterday doesnt detect classes or intellisense anymore
You can check if an object is destroyed by doing bool isDestroyed = theObject == null;
(the "instantiated" bit is irrelevant)
so in this case how would it be?
im generating a wave of enemy prefabs and want there to be both a wave limit and a limit to how many can spawn at once.
i just wanna check if one of the spawned enemies dies to reduce the remaining count
sounds like you want to store the instantiated enemies in a list
yea
so put them in a list.
var newEnemy = Instantiate(enemyPrefab);
myEnemyList.Add(newEnemy);```
and then when you destroy the enemy:
if (health < 0) {
EnemyManager.instance.ReportDeadEnemy(this.gameObject);
Destroy(this.gameObject);
}```
something like that
and the ReportDeadEnemy function can remove it from the list
is EnemyManager assuming that the name of my script is that?
yes
the name of the script that spawns enemies
and keeps a list of the enemies
also the .instance assumes that it's using a static instance reference
and that it's a singleton
the instancing is a bit new to me how would i now reference it on the if (hp < 0) statement in my enemy script? i have it written like this in enemymanager
I'm confused as to what you're confused about I guess.
well i just dont know how to define the instance fully i guess
cuz i dont know how to get the EnemyManager.instance part working
Well your public member there is Instance not instance
so you'd use that one naturally
Note c# has syntactic sugar for properties with only a getter. You can change the last line to public static EnemySpawner Instance => instance;
Though it should just be public static EnemySpawner Instance { get; private set; } with the backing field implicit.
Hi, for some reason I am always getting the same random values
private void Randomize()
{
Random.InitState(System.DateTime.Now.Millisecond);
rb.position = new Vector2(0, 0);
while(startingDirection.x == 0 || startingDirection.y == 0)
{
startingDirection.x = Random.Range(-1f, 2f) * 10;
startingDirection.y = Random.Range(-1f, 2f) * 10;
}
rb.velocity = startingDirection;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "RightWall")
{
score.AddA();
Randomize();
}
else if (collision.collider.name == "LeftWall")
{
score.AddB();
Randomize();
}
}
Any ideas why?
What value are you getting?
you init state every call
I even tried changing the seed each time the method is called
they change each time i hit play
but not each time the Randomize method is called
Stop reseeding every call
didnt work
void Awake()
{
Random.InitState(System.DateTime.Now.Millisecond);
}
//...```
then the problem is not in seed
run debugger over it
observe the values, something somewhere fails
public class Ball : MonoBehaviour
{
[SerializeField] private Vector2 startingDirection;
[SerializeField] private GameObject gameManager;
private Score score;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
score = gameManager.GetComponent<Score>();
rb.position = new Vector2(0, 0);
Randomize();
rb.velocity = startingDirection;
}
private void Randomize()
{
//Random.InitState(System.DateTime.Now.Millisecond);
rb.position = new Vector2(0, 0);
while(startingDirection.x == 0 || startingDirection.y == 0)
{
startingDirection.x = Random.Range(-1f, 2f) * 10;
startingDirection.y = Random.Range(-1f, 2f) * 10;
}
rb.velocity = startingDirection;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "RightWall")
{
score.AddA();
Randomize();
}
else if (collision.collider.name == "LeftWall")
{
score.AddB();
Randomize();
}
}
}
this is my entire code i dont know
I tried googling and the most I got was changing the seed
because when you search for non changing random value its people who dont know that the second max parameter doesnt include that number
Does this work the way you expect it to?
i mean my game runs I get no errors all good but
each time it "resets" the ball keeps coming at the same direction
it goes in the same direction over and over and over despite me doing Randomize() after each collision
it changes each time i run
alright, so at which time during consequtive calls the while condition will be true?
So Randomize is working per run.
Define reset.
divide by 10 its 0.5 and 0.149
if one of them is 0
Likely hardly ever if he's comparing floats.
and when is it 0?
in case the random value gave it a 0
which is never
It's 0 by default? What's the initial value of startingDirection?
This could always be false.
no it just can be 0
then if its false then the loop just ends
only when one of the component is 0 then reassign
first call you may have a 0,0 vector there
you get your random values
second call, since it retains the values from previous call
the vector is not 0, thus the loop never runs
So cs rb.position = ... while(false) ...
If the initial values are zero before assignment it will be false and never assigned.
ok ill get it out of the loop then
or
i can just do do while
problem is not the while
We're in agreement overall, just pointing stuff out.
problem is that you are reusing previous random values to generate a new random
hi
it works
public class Ball : MonoBehaviour
{
[SerializeField] private Vector2 startingDirection;
[SerializeField] private GameObject gameManager;
private Score score;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
score = gameManager.GetComponent<Score>();
startingDirection = new Vector2(0, 0);
rb.position = new Vector2(0, 0);
Randomize();
rb.velocity = startingDirection;
}
private void Randomize()
{
//Random.InitState(System.DateTime.Now.Millisecond);
rb.position = new Vector2(0, 0);
do
{
startingDirection.x = Random.Range(-1f, 2f) * 10;
startingDirection.y = Random.Range(-1f, 2f) * 10;
}
while (startingDirection.x == 0 || startingDirection.y == 0);
rb.velocity = startingDirection;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "RightWall")
{
score.AddA();
Randomize();
}
else if (collision.collider.name == "LeftWall")
{
score.AddB();
Randomize();
}
}
}
i added a do to the while so it will run for one time no matter what
private void Randomize()
{
//Random.InitState(System.DateTime.Now.Millisecond);
rb.position = new Vector2(0, 0);
Debug.Log($"Before Direction: {startingDirection}");
while(startingDirection.x == 0 || startingDirection.y == 0)
{
startingDirection.x = Random.Range(-1f, 2f) * 10;
startingDirection.y = Random.Range(-1f, 2f) * 10;
}
Debug.Log($"After Direction: {startingDirection}");
rb.velocity = startingDirection;
}```
and i sort of initialized startingDirection in the start just out of tiny suspicion
it works now
actually yes in this case you dont need the while loop
chance of actually hitting a 0 is astronomically low
i mean yessss but the probability
if its floating point 0 yes
like actual 0.0000000 yes
also if its a direction vector you dont need to do that
just use Random.insideUnitCircle
but if its 0.001 or anywhere in that range
and clamp the vector magnitude to ensure min/max speed
what if i just change the condition to x > -1 && x < 1
i need to read about it
regardless thanks for the assistance and help @ashen yoke @dusk apex
oh so it just
returns a value between -1 and 1?
oh it returns a vector2 with a range i set
perfect
why am I getting this error?
UnityEngine.Component.GetComponent[T] () (at <b41119cc6741409ea29f63c7f98de938>:0)
Menu.Awake () (at Assets/Menu.cs:16)```
```cs
public class Menu : MonoBehaviour
{
[SerializeField] private Volume gv;
private DepthOfField dof;
private bool active = false;
private void Awake()
{
dof = gv.GetComponent<DepthOfField>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
Time.timeScale = active ? 1.0f : 0.0f;
active = !active;
dof.active = active;
}
}
}
show me DepthOfField class
GetComponent requires that the requested component 'DepthOfField' derives from MonoBehaviour or Component or is an interface.
Assuming you are not deriving from less common stuff.
in script 😄
but this is your answer
how would i fix it
i just want to reference the DoF in the global volume and activate or deactivate it
You need to use TryGetSettings on the volume ref I think, not GetComponent
yes its not a component
so DoF is not a component its a setting of volume?
First, you need to retrieve the particular Volume Override using the generic TryGet<> function on the profile. If the Volume Profile does not contain that particular Volume Override and the TryGet<> function returns false, you can use the Add<> function to add the Volume Override.
so i use TryGetComponenet on the Volume to retrieve ?
i mean i dont see other trygets
No, look at the API
i am trying
Their example is with Fog
oh ok yes i was starting to get the idea i was just writing the VolumeProfile
[SerializeField] private Volume gv;
private VolumeProfile vp;
private bool active = false;
private void Awake()
{
vp = gv.sharedProfile;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
Time.timeScale = active ? 1.0f : 0.0f;
active = !active;
if(vp.TryGet<DepthOfField>(out var dof))
{
dof.active = active;
}
}
}
why is it not working
same error
Did you save?
You couldn't be getting a get component error if not using the statement.
i just noticed that i didnt
after i saw error at line 16 (vp = gv.sharedProfile) referring to DoF
nice
ye that's why I switched to regular vs
nice
I have a Texture2D with tile atlas. I also know UVs of each tile. I'm using that on a terrain mesh, and assign UVs to the mesh. Now I want to have a UI Button for each tile with Image component (like an inventory) . How can I use this tile atlas (Texture2D) to assign the proper tile image to the Tile if I know the UVs?
Do you have to find the scene root in order to FindObjectsOfType
I'm Searching for a type I know exists and has the component available
But it returns zero results
What I'm trying to do is find each component of a certain type
Show your code. No you don't need to find the scene root
Also make sure the objects You're looking for are ACTIVE
I will, it's just that Cold Turkey's locked my PC to force me to eat and I just wanted to know if it was the obvious thing.
I am considering using longs instead of float or double to store xp.
Perhaps use 2 or 3 of the digits for an imaginary decimal place
Is it silly, or does it make sense?
It's a wide, lossless range of values...
Good idea
OK so I've found that it was totally unecessary to call FindObjectsOfType since the class I was using was totally useless
Instead what I'm doing is storing a list of tags in the editor and using that
Faster and easier to understand
how can I make the int have a max value?
I'm trying to make an inventory system and trying to implement a max amount for each specific object
I've tried (value > 10) and (value == 10)
Mathf.Clamp() should work and so should the if statements?
I've tried that one too but I'm not sure if I'm using it right
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
hold on
myValue = Mathf.Clamp(myValue, minValue, maxValue);
Common mistake^^ Ppl forget to set it as a return value
how to do that?
The line just above
?
How many does it say is in the inventory?
Your problem is you don't clamp the actual value in your InventorySlot
Im confused by his code honestly
Me too
wdym?
When u add an item to the inventory theres an amount of "items" you add
Does the amount of items exceed ten?
it's related to other scriptableobjects
yeah
Ok so are you clamping the amount of inventory slots or items for one slot
items for one slot
Ok
So when you add items to a slot and the amount of items is over ten does it go over ten?
What are you actually trying to do? Because you're looping through every slot, add amount in existing slot, clamp that value, then create a new slot. I don't understand your goal
Yeah i dont see why the slots arent premade and then you just add to them?
is that the flaw?
I'm not even sure what your problem is at this point
No offense ofc
I am aware
Yeah, it's just confusing
Its just a weird design. You should watch a tutorial
What are you trying to achieve and what is your issue now ?
With more context than a simple clamp, we may be able to help
Can I develop iOS app with writing native code even though I develop Unity app?
Pls post your question in a single channel
when an item becomes ten I want it to stay always ten (that's the max) and when I continue receiving the item it will just create a new slot for it (adding an another item), I can send a recording to make it clear
OK. Thanks for the clarification 🙂
Sorry
I have this object that searches through all the game objects in a scene to find ones that have tags that match a list.
Once it has this list, it applies a gravitational force to rigidbody2D components of gameobjects in the list.
But that introduces a problem
Once that object no longer exists in the scene tree, it still has a reference in the list and fills the log with errors
I want the gravitator object to remove objects from the list as they're destroyed without a strong coupling
My mind jumps to the observer pattern, but how it's implemented with UnityEvents is confusing
Do I really need a separate class for each event and instance of it happening?
That seems obtuse
Dependecy injection
The ideal solution would be to just have an event handler that's trying to look for a message being sent like
"Hey I'm destroyed. You can remove me from the list now."
If you know for a fact which gameobjects are going to use gravity why have something else manage them? Why not just let themselves manage it?
Why cant u just remove them from the list? Event -= Listener;
Oh Unity Events* if you want something like that youll prolly have to use C# events
I usually make a public static Action<>
The reason I'm having the gravitator class do the pulling is because the number of objects being affected by gravity is unlikely to exceed the number of objects doing the gravity
When instantiating a gameobject while defining it's parent transform. How can I place it to the top of the children hierarchy?
I want to be able to drop stars, planets, etc. in the scene with preconfigured tags and have them just...
Work
I getchu
If the things being pulled were applying the gravity, then each time a new gravity source is introduced I'd have to go through every single object affected by gravity and update their data
I would use C# events and just have them listen to it
I will look more into C# lists events
Action and Func are delegate you know ?
The problem is created when we generate the list of targets to apply gravity to
There's nothing in there to say
Peep how i said outdated***
"Oh, and when you're destroyed please let me know"
So it just hangs
Like I found this article on the subject but it caused more confusion https://stackoverflow.com/questions/49903444/how-to-activate-trigger-when-gameobjects-are-destroyed#49903721
Also if something is removing "itself" from a List<> i believe its supposed to do so backwards instead of forward
I forget the exact thing but its opposite from how its normally done
This is a good point. I always forget to do it this way
i just remove at swap back.......
Hey guys, Help please. I am currently developing app in Unity.
I complete to develop some features, but I have realized that there is no method like Update method which can be executed when the app is going to background mode.
So, I decide to separate those features to Two parts.
One can be executed on Unity.
The other can be only executed on iOS or Android.
In this case, I think I must develop both Unity and iOS & Android.
Can I develop both env ?? If it is possible, can you recommend some keyword for research for beginner like me??
If it is impossible, I remove this unity app and develop each mobile app (iOS, Android). What should I do? Thanks
What is this feature you need Update in the background for
Playing Audio
Why is that in Update
what is the name of the tool people use for benchmarking? Like, if I need to compare 2 operations 10,000 times? I usually see a common output for diagnostics
Audio have to be played though specific interval for several minutes on background
How can I make the string include the variables ID & itemName, it won't work with $"{ID} - {itemName}" because it says I can't use
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'BaseItem.ID' and I can't use just public static int ID because ID is used in another script and then that script won't work.
[System.Serializable]
public class BaseItem
{
[SerializeField, HideInInspector] private new string elementName = "ID - Item Name";
public int ID;
public string itemName;
}
Show how you're accessing those values
public class ItemManager : MonoBehaviour
{
public ItemDatabase itemDataBase;
public BaseItem GetItemByID(int id)
{
return itemDataBase.items.Find(item => item.ID == id);
}
}```
```cs
public class GameManager : MonoBehaviour
{
public ItemManager itemManager;
public void UseItemByID(int id)
{
BaseItem item = itemManager.GetItemByID(id);
if (item != null)
{
item.UseItem();
}
}
}```
```cs
[CreateAssetMenu(fileName = "New Item Database", menuName = "New Database/Item Database")]
public class ItemDatabase : ScriptableObject
{
public List<BaseItem> items = new List<BaseItem>();
}```
||Reference the instance||
These are all the scripts working with that script
Thanks, but I already have done it. With this code
Application.runInBackground = true;
It doesn't work in mobile. I think this question is about PC, not mobile.
when I turn off my iPhone, Update method doesn't work any more
I dont see where you're trying to get ID and itemName
and what Dalphat says is what you need to do. reference the variable, not the class name
is it in elementName
does it need to be a variable? why not just override ToString
im trying to get my EnemySpawner to correctly instantiate enemies from the enemiesToSpawn list and it isnt spawning any. is there anything wrong with the way i did this?
i keep getting index out of bounds errors everytime at the var newEnemy line, so my if isnt checking if the list is null properly
ive tried a bunch of different ways and none worked
Is it possible to modify the size of the custom cursor?
does that check if Count > 0
Hello guys. I'm making 2D game and using Sprite Renderer for that ofc. Problem is it's not showing same on different devices. As you know Sprite no has Rect, Anchor feature.
How can i fix that problem? Should i convert all of them to Canvas Image? Thanks.
where do you take these sprites?
dont cross post, and i think you may include some example to demonstrate "not showing the same on different devices" (ie change the ratio)
if your game is ui-based (?) like card game or chess game then you may have to change it to ui element and use anchor to adjust
I'm creating my game scene with these sprites.
Yes, you either have to set the constant resolution or convert them to UI elements
I'm sorry for cross post. I just think code general will be more helper. Deleting same post on code beginner.
sprites don't have "different device feature"
so yes, you can use a script to convert them to UI
or manually
That's why i used that script for that but not working healthy. (if link share is not allowed i can delete it.)
Is there a way to detect objects based on a radial offset of a raycast?
have you done them by yourself?
I.E. give a raycast a sphere of detection around it
Yes.
yes, I think they just set a constant resolution there
you can also do that
SphereCast
ooo okay! I'll look into that
I did it but as i said not working healthy.
no it should work
What you suggest should i manually convert them to UI? So i can set them anchors.
well, you can do that too
you can use a simple script to convert them
But should i change all anchors them?
yes
I wouldnt change them like that
Like that.
If your trying to change a gameobject to something UI...thru script
That just feels....wrong
they can change constant buttons and images
if they don't act as a npcs or players in their game
I have done it to create images from my sprites that were originally used as players, game fields and enemies in order to display them in level creator
animator..
Oh yes so many objects have animations..
you'd better used the link you have sent to make a constant resolution
Here is result if i use that. Look that animal's placeholders...
I didn't set them in editor. Position was okay in editor.
use constant resolution.
this way doesn't seem moveable
so you don't scroll it
that's why no reason to use different resolutions
just full window
the image you have sent is 1196x670
you can use that as your resolution
nice game
I was made 2D game but didn't have this problem before. I really don't know what is the problem..
what is even the problem?
Gamebackground have gap on some mobile devices. Because they have bigger screen than i'm working on. I'm working on 2532 x 1170 pixels. Also on the video you can see i have circle shapes on right side. They not showing on smaller devices, i mean half of them are showing.
For background gap problem i wrote this. It solves it but the other problems...
Didn't you use UI button or image for your UI ?
I used for "You Won" screen. It have Text and Button UI object.
Yes, but the circle on the right side is ui too
it's shouldn't be anything else than ui
Because it's not playable?
Hmm
It's not a question of being playable or not
yes, many games have this
have you ever seen a game with black background on the borders?
No ever because they are solving that problem somehow
well, no
From my POV, you're game is a giant UI with draggable element and VFX/Animations to add some juice
If you want it to be responsive, use UI
but I don't think it's a nice thing to do
you can see that resolutions are different
so the balls on the phone don't even look like a circle
so yes, lot's of games use black background
found in the internet
What you suggest me for that?
Hmm but if they will use bigger background image it will solve it?
Okay but so many objects have animations?
That you can use the anchors
they will have to make background bigger
so that it will fit for all devices
I mean, you can simply modify the part on the right
You did this as UI, right ?
No i didn't they are sprite renderer too.
This part should be UI
so it will look different on different devices with no black bg
So to summarize. If i use bigger background image for gap problem and for right side placeholders i should use UI?
it's not animated, it's an interface the player can interact with and it should be place responsively in the overlay
Okay i'm chancing them to UI object.
Canvas should be Constanst Pixel Size?
Or should i make it Scale with screen size again?
It's last question. Sorry for taking time..
Scale with Screen Size otherwise it won't be responsive
Can generics be used in any way in Unity? Case: I have a generic PoolController script to pool instances of objects. List<GameObject> itemsInPool worked fine up to now. I'm in a need to use a interface PooleableItem<T>{ void Init(T params)} function for this to reset some common properties. I know interfaces cannot be serialized so perhaps I can use abstract class for that. But then those items cannot be serialized, I don't know if I'm not overcomplicating this.
you can use generics just fine
Generics are used all over the place and can be used wherever you want
but if I can't put them there, doesn't t mean it won't be serialized? if yes then I have to serialize those manually?
Interfaces and generics don't really have anything to do with each other
specifically, if you have a Generic monobehaviour, that will work fine in C#. But you can't add a generic monobehaviour as a component
concrete genericized types can certainly be serialized
For example, you can serialize a List<int>
you only really run into issues with inspector. As Unity won't display many types by default. ie Dictionaries. You need something special to serialize them.
And you can still do it. It just doesn't come out of the box
Let me put it this way. There's no such thing as a class that has a "List<T>" field. It will always be a field of some specific conrete type such as List<int>. Same goes if you have like an ObjectPool<T>. You would have an ObjectPool<Enemy> in any real implementation
now whether that thing is serializable or not is a different story but it wouldn't be specifically because of the generics
But I can't do something like this, right?
{
[SerializeField] PooleableItem<T> itemsInPool;```
There's a plugin someone made that lets you do that
but in general no
if you write that monobehavior like that, you can't even add it as a component
you can do this though:
public class EnemyPoolController : MonoBehaviour
{
[SerializeField] PooleableItem<Monster> monsterPool;```
so the SerializeField poolableitem doesn't even come into play
not in the inspector, but you can at runtime with AddComponent 😉
at that point, don't you give it a concrete type?
ie not adding PoolController<T>, but PoolController<MyType>
well you can do cs public class MonsterPool : Pool<Monster>
yes as in the example
it's PoolableItem<Monster>
I mean right now I have the code below, and I'm just thinking how if I can change it to still have just one PoolController script instead of creating new one for each type 😛 ```
public class PoolController : MonoBehaviour
{
[SerializeField] List<GameObject> itemsInPool;
This was answer to the above
Thanks all. I suppose it's the most straightforward to create those separately as: public class MonsterPool : Pool<Monster>
yes it is
if you want to add it to inspector and work with it
without adding extra things
can i download the cinemachine from unity 2017.1 somewhere like github or archive.org?
like has anyone a link
i need it for 5.6
Hello, Any Native audio plug-in Hello world example or articles??
Idk where this fits so I'll put it here - I got these errors when I updated the unity version of my project and tried to build it
Error 1
Error 2
Instead of discerning them by types, why not add a field that contains the necessary information? (Such as an Enum)
Error 3
I haven't come across this specific error but first thing you do when something breaks after updating is deleting the library folder, which forces Unity to rebuild it from 0
where exactly do I find it
It's right next to Assets, in your project's root
Do keep in mind this takes a while
so packages?
what is a fast way to just count the number of bits set true in a long/int etc?
is there a way that does not involve looping
impossible, change the implementation of your bit vector
would it work if I worked in uint64 instead?
I tried to use BitOperations, but I don't think I have that namespace in unity. And I heard about CLS compliance being an issue
yeah i found it and deleted it but the errors are still there
just to give a full picture, I'm trying to use a long as a way to hold 64 booleans, where I can do bitwise math etc.
Well looks like PopCount added in .NET 7 😄
Not in Unity ™️
You can always look into .NET impl tho https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Numerics/BitOperations.cs,496
I have a component that is added at runtime via AddComponent and I need it to have a reference to a Material. Is there a better way to have a script that never touches the inspector outside of play mode have a reference to an asset than using Resources? I have managed to avoid using Resources this far and it'd be annoying to use it for this one material
that helps a lot. ty
I would like to know before I go too deep if I should do what I'm doing as long, vs Uint64, vs something else that will make my life easier
I'm going through a painful refactor right now, and want to avoid making it even more painful lol
finally had a good excuse to use WolframAlpha.com I figured f(x) = ((x (1 - sqrt(1 - z^2)))/sqrt(1 - z^2) + x)^2 but needed it simplified... Wolfram knocked it down to f(x) = x^2/(1 - z^2)☀️ 💩
O(1) algorithm for long... id even understand how they comes up with this algorithm....
Put the reference to some other script (possibly singleton?) 😄
Would anyone be willing to help me make a unity script to make interacting with my api easier?
Please ping me/dm me if you do.
I guess ¯_(ツ)_/¯
Just wish you could use those editor-defined defaults at runtime
_ _
C = collider
R = Renderer
I'm not sure how to ask this.
I want to get the render when recast hovers over collider even when the render isnt on the collider but a parent or child.
Debug.Log(hit.collider.GetComponent<Renderer>().material.name);
Renderer rend = hit.collider.GetComponentInParent<Renderer>();
if (rend != null) {
// whatever
}```
(despite its name, GetComponentInParent also searches that object before going up, so it works even if you hit the topmost object)
in this case I would honestly put a component on the ElectricWire variant object. Let's call it Wire for example. Wire can have a reference to its renderer. So you can do this:
Wire wire = hit.collider.GetComponentInParent<Wire>();
if (wire != null) {
wire.ShowElectricShock(); // or whatever you're trying to do. In this function you would manipulate the renderer as desired.
}```
this way will work even when it's a sibling of the parent(s) of the collider, since the Wire is the root of the hierarchy
I would also do that. It is way more robust.
it also lets you manage when this interaction with the wire conflicts with or interacts with other wire interactions etc in a central place
I'm making a pick up script and i want anything in a pickup layer to glow when hover the pickup collider.
Yeah so attach a script and search for that instead. That way you have room for improvement, say when you want to display the glow in a different color, or some custom text
Ok so make a "SelectionGlow" component and attach it to the ElectricWire Variant object and the pickUp object
and use GetComponentInParent<SelectionGlow>() and call StartGlowing() / StopGlowing() on it as necessary
dose that mean I'm going to have to put a script on the collider that references the wire renderer
//put this on the colidder object child obj
public Renderer ren;
not on the collider
on the root object of the selectable/glowy thing
I am unable to GetConponent<rootObject> from the child collider
what?
What does that even mean?
GetComponentInParent<SelectionGlow>() as mentioned already
i dont know how to get the root object from the child
then why want i able to GetComponentInParent<Renderer>() rootObject.
Why would you do that?
Have you not been reading anything I've been writing?
ill make a selection script that gose on the parent obj that the makes parent render materal glow.
yes, you should already have that if you are going to be making selectable things
Basically - the glowing renderer thing is at least one step removed from the script that actually does raycasting
that should indeed be a script that just deals with a "selectable" component
the selectable component can handle the glowing bit
a powerful website for storing and sharing text and code snippets. completely free and open source.
The gameobject (player) moves in x-axis when pressing "w"
the rotation works fine
but it goes horizontal instead of vertical
also no backwards movement
Line 38 is not correct, you should be using transform.forward if you want to go forwards with the vertical axis
Assuming the object's "forward" points correctly to the local Z axis
Vector3.forward will give World regardless transform orientation @hard quiver
now it can only rotate left-right not forward-backward movement
transform.up if you want it to move upwards
it worked!
Forwards is not upwards fyi
thx, i knew it was something stupid
Upwards is Y, forwards is Z
any way to improve this portion of my level gen that's determining the contiguous portion of the level? Basically freezes at large map sizes. TestRoom is just a class that contains some info ab the room like the walkValue and what connections it has. rooms[maxSize.x / 2, maxSize.y / 2] is guaranteed to exist.
// walk rooms
Queue<TestRoom> open = new();
open.Enqueue(rooms[maxSize.x / 2, maxSize.y / 2]);
int walkCount = 1;
bool init = false;
while (open.Count > 0)
{
TestRoom working = open.Dequeue();
working.ran = true;
IEnumerable<TestRoom> gotRooms = GetNeighborsAdjacent((int)working.transform.position.x, (int)working.transform.position.z);
int max = 0;
int index = 0;
foreach (TestRoom room in gotRooms)
{
if (room != null)
{
working.connections |= (Connections)(1 << index);
if (room.walkValue > max)
max = room.walkValue;
if (room.walkValue == 0)
{
open.Enqueue(room);
walkCount++;
}
}
index++;
}
working.walkValue = init ? max + 1 : 1;
init = true;
if (slow)
yield return null;
}
put a yield inside the foreach loop
If that's not good enough you'll have to break it doen even further
but wouldn't that just slow it down technically, not actually make it faster?
yes it would help alleviate the "freezing"
you can use the profiler to see what the issue is with the speed
hold on, I actually noticed I forgot to include .Except(open) after GetNeighborsAdjacent, which returns an array of 4, up/down/left/right.
perhaps, for example, GetNeighborsAdjacent is allocating memory which can make this quite slow
ah it is allocating memory! I should reuse an array instead
I would start with the profiler
to see what the bottleneck is
but yea it's likely reusing a List will be better
I feel like I'm missing something very basic. I'm trying out a tutorial for a basic field of view. Trying to do a 2D raycast for generating a vertex point. However, the raycast is returning a collider, but an empty point (0,0) for every raycast. Any ideas why the raycast wouldn't be returning a point? `float angle = 0f;
float angleIncrease = FoV / RayCount;
Vector3 origin = Vector3.zero;
Vector3[] verticies = new Vector3[RayCount + 1 + 1];
Vector2[] uv = new Vector2[verticies.Length];
int[] triangles = new int[RayCount * 3];
verticies[0] = origin;
int vertIndex = 1;
int triIndex = 0;
for(int i = 0; i <= RayCount; i++)
{
Vector3 vertex;
RaycastHit2D ray = Physics2D.Raycast(origin, GetVectorFromAngle(angle), ViewDistance);
if (ray.collider == null)
{
vertex = origin + GetVectorFromAngle(angle) * ViewDistance;
}
else
{
vertex = ray.point;
}
verticies[vertIndex] = vertex;
if (i > 0)
{
triangles[triIndex + 0] = 0;
triangles[triIndex + 1] = vertIndex - 1;
triangles[triIndex + 2] = vertIndex;
triIndex += 3;
}
vertIndex++;
angle -= angleIncrease;
}`
do I need to add anything to the code, or how do I see specifically where the bottleneck is with the profiler?
how do you know it's returning an "empty" point?
working.ran - I assume it's a flag that tells that the room was visited.
You're not using it in the loop, you're probably rescanning rooms that were already visited.
If it's not its use, then consider adding a isVisited boolean
I usually use a HashSet<TestRoom> to track which rooms have been visited already
I'm debugging, and in visual studio the collider is not null, and the .point is always 0,0
Yeah, and paired with a recursive method, looks somewhat cleaner
perhaps your raycast is starting inside some object?
oh I definitely wouldn't use recursion 😉
Also a good idea! thanks!
Do buttons save their listeners when the same scene is loaded second time?
No, they don't, so listeners have to be added once more, right?