#archived-code-general
1 messages ยท Page 193 of 1
you haven't actually provided any actual details about what it is you are doing so ๐คทโโ๏ธ
You can do whatever you want as long as it's compiled into the built game
and using editor-only code won't build, so you will have to exclude the bits that use editor code
I pretty much have a bunch of listed weapons i made using a custom editor. And since that doesnt work i cant switch weapons let alone save it
Would scriptable objects work as a better replacement then
You made them in the custom editor but where is that data stored?
You need to give off more specific info but it does sound like you want SO's for this
yeah it sounds like you're just not actually serializing the data. of course you're also being super vague about what exactly you're doing so we can really only speculate until you provide detail
Data is stored in a different script, im just using a custom editor to make things easier for me. So this "list" I made is when i used a custom editor but the data from that list, like the name of the weapon, damage, etc is stored in a diff script
NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[prefabIndex]; why unity shows error here? What is wrong with it?
#archived-networking but also provide the error
I dont really have any other way to make an organized list of weapons without using custom editor
I have a mesh with 3 submeshes
can i have all these submeshes use a shared material
then use the material property block to modify the material property for each sub mesh?
if so how?
No no
you can make it in the custom editor
you just can't keep it there
If you keep your organised list somewhere outside of an editor related tool
it will
Network config doesn't provide Network prefabs
again, #archived-networking
and share the full actual error
help
I mean the list isnt technically inside the custom editor script. All dat data is stored somewhere elsre but i use custom editors to make making the list easier
Where is it?
you should really share the relevant code so nobody has to guess at what you are actually doing
Got it
Is there a good and quick way to move an item in a list to a different index without having to redo the entire list?
like if something is at [6] and i wanna make it [0]. All good if i gotta for loop it just curious if im missing anything cool
like swap the objects so that what was at 6 is now at 0 and vice versa, or actually remove it from the list and add it back at index 0? and also is it actually a List<T> or an array because that matters as well
i got like 5 pictures here
actual list
wanna put 6 at 0's position and have the list push up to reflect the change
can i send it here
no
!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.
ok
what does that do
oh
ty
can i atleast send 1 pic here on what the inspector looks like then paste code or are images just not allowed
nah those type of screenshots are fine
๐ 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.
since it's an actual List<T> you can just remove it from the list then insert it at 0. otherwise you could loop backwards over the list and just keep swapping it to a higher index to move everything else down accordingly
you're meant to read the bot's message not use the command again
yeah just realised
Wait wym Insert it at 0?
im assuming not list[0] = mything
did i do it right
#archived-code-general message
tells you how to share the code
but doesnt really matter
so i did do it wrong then
did you even bother reading the bot's message? or do you think 300+ lines is not a large block of code?
gotta use one of the sites for big scripts homie
itd probs be like 1k or smth lol
oh shit waddup
big blessings โค๏ธ
just keep in mind that the larger your list, the slower the operation will be. the other way i described can be faster (though if you're moving something from the end of the list it'll basically be the same speed)
ok so
i clicked on the link to Paste ofCode
and uhh
clicked enter...
im supposed to put a link right
I am using a GUILayout.BeginScrollView to display a debug console in my built application that allows me to scroll through the messages.
However, I cannot figure out how to change the background color of the GUILayout.BeginScrollView so I can read the text easily.
How can I set the background color? GUI.backgroundColor = Color.gray; does nothing.
i don't really see anything that stands out as being wrong about this. can you provide some details about what is actually happening? and maybe also the relevant code where the issue actually happens?
I was able to find a, rather ugly, work-around by putting an empty TextArea behind my GUILayout.BeginScrollView, and because the TextArea has a gray background I'm able to read the log text easily and scroll through its history.
Is there an incremental build version of BuildPipeline.BuildPlayer?
Any can help me with this thanks
Hello, I am trying to create a spawn script with atleast 10k GameObjects, however when I do this the FPS drop substantially. I tried to do Object Pooling and GPU Instancing and doesnt seem to improve. Any tips?
to hell game objects, learn dots ๐
that sounds like a "time to switch to ECS" kind of problem
consider me a begginer, this is a entry level exam ๐
do you have some guide I could check out for ECS?
then you need to learn how to use profiler and optimize your scripts
you have an exam that requires spawning 10k objects? ๐ค
#1064581837055348857 has all resources pinned
basically the exam is to simulate a wild fire
and as trees for now I am using simple cubes
and when I spawn until around 7k everything is great, but anything more than that is too much to handle
note that this must also be done in unity 2020, so im not sure if ECS is available there
only very old one, which you don't really want
I see, what would be your approach to this then?
and neither you have enough time to learn it anyway
thank you kindly
profiler manual will get you started
i see, thank you very much
I've been stuck on something for hours. How would I achieve this using instantiate? I've looked online a bunch and people only seem to reference Camera.ScreenToWorldPoint but I've tried to script something around that and it's not working
I know this probably looks really stupid, but this is what I tried to do, but theyre just spawning at the top right
What is the unwanted behavior?
man i really thought i fixed it, this is my current code
ill record a gif of the behaviour, 1 sec
theyre just instantiating at the top right
Hmm, if it were me.. I'd go about it in this fashion... cs float x = Random.value; float y = Random.value; float offsetX = x < 0.5f ? offsetA : offsetB; float offsetY = y < 0.5f ? offsetC : offsetD; x = offsetX + x * hThickness; y = offsetY + y * vThickness; Vector3 spawnPoint = new Vector3(x, y); ...The assumed coordinate system is that top left is (0,0) and bottom right is (1, 1)
Cache those values and see where they're located.
Log the spawn point vector.
Images of code are difficult to work with..
what do you mean by this sorry
how do you do the coding thing
where you make it the little window
How to post !code (link for large code blocks else you can inline with backticks)
๐ 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.
test
ok
float x = Random.value;
float y = Random.value;
float offsetX = x < 0.5f ? -10.25f : 9.25f;
float offsetY = y < 0.5f ? 6.25f : -5.5f;
x = offsetX + x * 0.75f;
y = offsetY + y * 0.75f;
Vector2 spawnPos = new Vector2(x, y);
Instantiate(enemyGroup.enemyPrefab, spawnPos, Quaternion.identity);
so i've done this but it's not working
it's an improvement tho
now they're spawning at the 4 corners
btw i really appreciate your help, even if we don't end on the system working correct, just any learning is valuable
Ah yeah, I only accounted for the corners.```cs
bool vertical = Random.value < 0.5f;//Left-right or up-down
float x = Random.value;
float y = Random.value;
float offsetX;
float offsetY;
if(vertical)//Left-right
{
offsetX = x < 0.5f ? -10.25f : 9.25f;
offsetY = Random.Range(6.25f, -5.5f);
}
else//Up-down
{
offsetX = Random.Range(-10.25f, 9.25f);
offsetY = y < 0.5f ? 6.25f : -5.5f;
}
x = offsetX + x * 0.75f;
y = offsetY + y * 0.75f;
Vector2 spawnPos = new Vector2(x, y);
Instantiate(enemyGroup.enemyPrefab, spawnPos, Quaternion.identity);```
for "height of area" and "width of area"
is there a way to use the camera bounds for this information
I'm unsure off the top of my head 
ok nw
sorry to confirm real quick
for height of area
would it be the worldpoint of the bottom of the screen + the worldpoint of the top of the screen
Wait that might not work..
Try this @haughty badger
it worked thank you so much
Bottom bound probably needs some adjusting but you've probably got that.
Forgot that unity coordinate system is bottom left (0, 0) to top right (1, 1)
sorry for the long reply, was busy with something else. But there isnt really any problem with the code, everything seems to be working in editor, maybe its just that the custom editor doesnt work in build, so i just ended up switching to using SO's
yeah i can mess with it now that it's working
yes, the custom editor does not work in a build. that is a given because the custom editor is for the editor. you haven't actually said what the issue is in a build though. all you've said so far is that something isn't working
pretty much the weapons arent switching in the build
you should really learn how to describe issues. and see #854851968446365696 for what to include when asking for help because you aren't providing any actionable details
when using SO's it doessnt work either
cant really give a good detail cuz i myself dont even know the real issue as well
well surely you know what is actually happening in the game. and you of course have access to the code and logs
ye
sorry if this the wrong sction to ask, but does anyone know how to link a github repository to a already existing unity project?
Try asking in #๐ปโunity-talk
ok thanks
Hello, I want to rotate my object exactly 90 degrees but obj.transform.Rotate() function sometimes returns incorect numbers such as 89.7. How do I prevent that?
code:
public void RotateFreeTile()
{
reference.Rotate(new(0, 0, 90));
var freeTileRotation = Matrix4x4.Rotate(reference.rotation);
tileMap.SetTransformMatrix(freeTileViewPosition, freeTileRotation);
freeTile.RotationMatrix = freeTileRotation;
lastRotation = freeTileRotation;
}
I'd do osmething like this:
int orientation = 0;
void RotateFreeTile() {
orientation += 1;
orientation %= 4;
Matrix4x4 mat = Matrix4x4.Rotate(Quaternion.Euler(0, 0, orientation * 90));
tileMap.SetTransformMatrix(freeTileViewPosition, mat);
freeTile.RotationMatrix = mat;
}```
(get rid of this "reference" object)
How do add a listener that will get current value of the slider?
.AddListener(OnSliderValueChanged)
doesn't it take a float parameter?
I guess assuming OnSliderValueChanged accepts a float parameter that will work^
why my property drawer isnt working?
Is your editor using IMGUI? Perhaps because you have an annoying package like Naughty Attributes installed that has overridden every editor to use IMGUI
i think im using it
You are inspecting the scene view
you need to inspect the inspector and try to pick elements in it
That's IMGUI. You likely have an editor in your project that is forcing it to be that way
so all my editors in the project need to be UI Toolkit, for unity to render in UI Toolkit?
No
Just that one
but there can be editors that override all Objects/Monobehaviours/ScriptableObjects, it's a common shitty way to add support for buttons via attributes
ohhh
i have one script that overrides mono
it placed a mini title at the top of the script, but even if i removed it, i still get this
if you still have that MonoBehaviour editor that is using IMGUI then it's still in use regardless of what features are being used that it is there for
Either your editor has OnInspectorGUI in it for some reason (and you're not using a modern enough version that would use UITK by default)
or you still have an Editor that is overriding it
Or you have Edit/Project Settings/Editor/Use IMGUI Default Inspector enabled
cant find Use IMGUI Default Inspector
not for inspector keyword
Might not exist in your version, but you should probably just search IMGUI
nothing
but its 2021.3.6f1
but uitoolkit is installed as u can see in this ss
I know, the editor uses it, it's built in
You should always be able to make a custom editor of your own for that type and write it using UI Toolkit
Pretty sure it just needs to call InspectorElement.FillDefaultInspector on the root you return in CreateInspectorGUI to draw the default inspector
I'm trying to change the color of a UI image from a button script, but I can't get a reference to it
"Image" isn't a class apparently
neither is button
Image is a class
same with Button
yeah looks like I have to import unityengine.ui?
Your IDE should be auto suggesting the using directives to you
if it's not you need to configure it
but yes, the full class name is UnityEngine.UI.Image
thanks
i tried that but didnt work, also i had created a custom editor script and it worked just for this simple property drawer it wont
Oh ok, thanks
Hey,
I'm trying to use Handles.DrawSolidRectangleWithOutline inside an EditorWindow.
I registered to SceneView.duringSceneGui callback in OnEnable (+unregistered in OnDisable).
However it seems the DrawSolidRectangleWithOutline method uses screen space. Specifically the scene view screen.
So drawing at from (0,0) to (200,200) when the size of it is (400, 400) draws the top left quad.
How can I convert a scene object position coordinates to that scene view coordinates?
i copied the whole ingredients code fom unity and still the same no GUI..., i dont understand why https://docs.unity3d.com/ScriptReference/PropertyDrawer.html
Hi all - I know c# fairly well but don't understand all the complications of the architecture for building a unity game - what is the best resource for me to understand things like how to structure the architecture of the project?
!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/
Ok will follow those thanks
Hello!
I'm trying to create a key bind system where users can choose which key is used for every action.
The problem is, when I press "A" on my keyboard, the input system detects it as KeyCode.Q (I have a AZERTY keyboard).
Everything works but it looks bad, if I want to bind to A, it shows Q...
Is there a way to convert the "physical keys" used by the input system to the name of that key on the user's keyboard? I thought it would be easy but I can't find anything on Internet ๐ค
I recommend using the new input system which has rebinding built in
Oh ok I'll look at that, thank you!
But since I've already implemented everything using the old one, it would be easier for me if there was a solution with the old one ๐
as per https://docs.unity3d.com/ScriptReference/KeyCode.html:
Key codes returned by Event.keyCode. These map directly to a physical key on the keyboard. If "Use Physical Keys" is enabled in Input Manager settings, these map directly to a physical key on the keyboard. If "Use Physical Keys" is disabled these map to language dependent mapping, different for every platform and cannot be guaranteed to work. "Use Physical Keys" is enabled by default from 2022.1
Ah so I should disable it?
But then the problem is the default keys will be broken for some keyboards ๐ข
what should I set my orthographic camera size to?
with keybaord layouts etc
whatever you want
There's an explanation here of what it means: https://docs.unity3d.com/ScriptReference/Camera-orthographicSize.html
Dont know if this is excatly the right channel but why wont my unity even download been on valdating for hours
i have a line renderer and I noticed that dealing with orthographic view is distoring the perspective of those rendered elements positions relative to the camera... when compared to the canvas? I am using Screen Space - Camera for the canvas
if I change to Perspective view, it appears to fix it, but I don't understand why
and I'm in a 2D game so I dont think I'd want Perspetive view either
show what you mean perhaps?
orthographic cameras don't have any perspective effects
so i am fixing my scene right now (not ignoring you) sorry.... I had confusion over rendering a large image with it's native resolution vs the screen size
the background image is very large, twice 1080p resolution appx... so I thought I had to use native resolution for that image but I just realized that has nothing to do with the image quality
and it was messing up the position of the orthographic stuff too, bc 0,0 should be the top right for an ortho camera right
screen space coordinates have nothing to do with the camera projection
really!?
yes
ScreenSpace is from bottom left
why does this coordinate for the centerpoint of the container say 0,0, but it's floating so far off the screen space?
looks like you're confused between UI elements and world space objects
but that position is the center of the Map RectTransform
If you're working on UI elements you should use the rect tool
and I suggest enabling gizmos too
since you're using the "center" anchor preset for this object, it is considered 0,0 when it's in the center of its parent
I imagine your image there is probably a SpriteRenderer in world space though
so you're trying to mix up world space things and UI elements
which is no good
so i need to move all that outside the canvas?
its a map
if this is UI stuff, it all definitely belongs inside the canvas
if it's not UI, it belongs outside the canvas
i can't render the objects with a shader correctly if I use UI images
so i have to use sprite renderer
Then you are stuck without the UI tools
and can't use RectTransforms/canvases etc
and you won't be able to mix it with UI stuff either
You can definitely use shaders in UI though
you just have to write UI shaders
is there a list of UI tools somewhere?
I don't really understand what you're saying either, If I'm using orthographic view I should be able to mix the position of UI and non ui elements, as they exist in the same space and their positions regardless should be in the same space?
since perspective isnt involved
No. UI elements exist in Screen Space (assuming you're using one of the two screen space canvas modes)
everything else is in world space
no, because I deselected Use World Space in my line renderer
so it is not in World Space
and yet, the positions are off by just a bit
let me get an image of that
LineRenderer is in world space
that checkbox determines whether the positions in its position list are local or world space
but it's still a world space renderer
like most things
is there a solution for rendering lines that is in the UI space?
if you set your canvas to Screen Space - Camera then as long as the plane distance of the canvas is further away than the line renderer, the LR will be in front
yes which is what i did
and it shows
one min let me get an original picture of the actual issue
its a bit hard to see because its so zoomed out, sorry
but, its drawing lines between the positions of those little sun images
but it's drawing them off the screen by like thousands of units
because the suns are Image components on the UI
which are in screen space
you will need convert between screen and world space coordinates if you want it to line up properly
I'm guessing this btw
you haven't actually explained what they are
or where they are
etc
so i'm mostly working on guesswork here
its probably because i'm changing the parent and then setting the position in my script
i had this issue before
so, I changed the position of the coordinates for the Line renderer to be localPosition of those objects, and it fixed it
which I guess makes sense bc i'm not using World Space coordinates
for the LR
im still confused about why the canvas position is put in this strange location
not sure where to ask about this, but it's about fonts, specifically how to make .ttf files. The objective is to use the 10 images i have at my disposal to make some sort of font that i'll use in my game to display something like the stock of an item in the player's inventory, etc. I thought of using shaders to accomplish this instead, but it looked overly complicated after trying my hand at it for some time, or more like the procedure of making it was too impractical. The images are all 16x16, oh but ignore the test1.png and test2.png things, i just made those to test out the shader thing
oh wait, if i color my textmeshpro component after using the special font, it'll color.. right?
i'm guessing it would, just as a spriterenderer would've colored one of these images
there's free utilities out there to make ttf files (i haven't done it for ages but google brings up typelight which looks pretty good) but if you want to display these exact images making a ttf is probably not the way to go
TMP sprite assets would probably be better, no idea if those get colored the same as the text around htem
I need Friends really badly and i want to make a game so im 13 my name is Christopher and I use unity if you want to make a game with me reply
Can someone help me better understand a state machine pattern for things like enemy AI? So far i have an abstract base State and multiple states that inherit from it (e.g. Idle State). I also have a StateManager that inherits from MonoBehaviour, as well as a generic Enemy script that contains things such as hp/maxSpeed etc.
My current goal is to make it so that an enemy changes from its IdleState to ChasingState when a player is within X radius. My question is who should be in charge of changing the state? Should the State itself have a reference to the StateManager and do something like:
//IdleState.cs
stateManager.ChangeState(chaseState);
Or should it simply have a function that the state manager calls, such as:
//StateManager.cs
var newState = currState.Update();
var currState = newState //redundant but just to make a point
//IdleState.cs - Update()
if(playerWithinRadius){
return chaseState;
}
return this;
And in both of these cases, how should i get access to game objects like Player or Enemy, should these be passed down from the stateManager, added through the inspector or just using GetComponent?
Don't exactly remember how I did this myself, but I had a main script on the npc which handled the actions for states and changing the state if given conditions were met. Though there are a bunch of tutorials that come up when googling "Unity finite state machine" or "finite state machine" which you could follow if you want to, unless you are already following one. For getting the objects you could pass them down or make a separate script that holds all that data and access it if you want or whatever other solution fits you. Just make sure to cache the GetComponent<T>() if you are going to call it a lot
I was already looking at a few tutorials but they each kinda seemed to handle it in different ways. One had all the logic in the main Enemy script, and simply used the state machine to change between states (which kinda felt like it didn't really achieve much over just storing the current state as an enum). A few others just used completely different division of labour, and the unity learn with code tutorial used an entirely different one on its own, which felt a bit overengineered
I'm just thinking of what architecture will lead to least headaches later down the line when i realize i'll want a reference to X and start getting headaches because of the way i've laid everything out
not to mention good design principles, as in how much is a state supposed to know etc.
Ah, found it, this is what I used and it did seem a bit over-the-top for me at first, but when I took a bit of time to look at it, it got very simple and easy to use & understand and implement new stuff into https://www.toptal.com/unity-unity3d/unity-ai-development-finite-state-machine-tutorial
How to keep a port open for 'listening' inside of Unity ?
port for what? Editor or Runtime?
for incoming messages from browsers for example, at runtime
so which protocol? HTTP or WebSockets?
thinking websockets , I assume unity can do the same websockets client as regular c# app ?
unfortunately not
that's unfortunate, is there any alternatives?
I see their netcode page has something for this, but seems like a clunky solution.
what is your target build platform? WebGL?
maybe down the line but not a priority, it would be useful to have it work there as well.
desktop/mobile mainly
Ok, WebSockets for WebGL in Unity is a real pain, you have to make an Emscripten inteface between Unity and the browser.
However I have a WebSocketWrapper class I build for other Unity platforms, I can send it to you if you want
that would be awesome! I'd love to take a look / learn
See DM
I want to make it so that my player can only run for a limited time how would I input that?
https://unity.huh.how/info/basics you should post your code if you can't get the basics to work
wait
make some basic timer logic with a counter that either checks against something like sprintUntil = Time.time + sprintDuration, or uses sprintTimer += Time.deltaTime
heres my code, just for an fyi, ```cs
using UnityEngine;
public class ChangeMeshOnCollision : MonoBehaviour
{
public Mesh newMesh; // The new mesh to assign when a collision occurs
private MeshFilter meshFilter; // Reference to the MeshFilter component
private void Start()
{
meshFilter = GetComponent<MeshFilter>();
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
// Check if a new mesh has been assigned
if (newMesh != null && meshFilter != null)
{
meshFilter.mesh = newMesh;
}
else
{
Debug.LogWarning("New mesh or MeshFilter not assigned.");
}
}
}
}
If you're just having issues with the collision message I have more troubleshooting for those https://unity.huh.how/programming/physics-messages
alright
it hasnt worked
Show the setup of your objects then, because the guide is extremely thorough
but ther's no collider on that object, so it can never hit anything
but still doesnt work
tried it
i added the collider
already
and it doesnt trigger
Neither of your objects have a rigidbody, so they don't match in the matrix. Also, it's unclear whether you don't additionally have any of the other issues in the guide
even with the rigidbodys
it does not work
listen can u just help me please? im trying to get an explanation from somebody who knows more then me
not debugging
I've locked my cursor but I only want it locked in a specific scene is there a way to do that?
Only run the locking code in that specific scene, and unlock it when you leave it?
what do you use to only run the locking code in a specific scene?
my locking code
its just on a script for my player character
add the script to one scene, not all of them
don't add it to an object that is present in all the scenes
the player is only present in the one scene
then you just need to unlock it when you leave the scene, presumably if the player is not using DontDestroyOnLoad then you can unlock it when the player is destroyed
How can something collide if it has no collider?
Ah, vertx posted the walthrough for collisions that should solve it with even a quick glance
Step 1 is to read the error message
Nothing is assigned to the variable but what I want is to grab the previous sprint time
Show the variable where it is declared
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed;
[SerializeField] float currentStamina = 0f;
[SerializeField] float burnStamina = 2f;
[SerializeField] float replenStamina = 0.05f;
[SerializeField] float delayStamina = 2f;
[SerializeField] float maxStamina = 10f;
public bool running = false;
private float lastSprintTime;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
running = true;
Debug.Log("yep");
}
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
{
if (running)
{
speed = 50;
currentStamina -= (burnStamina * Time.deltaTime);
lastSprintTime = Time.time;
if (currentStamina < 0)
{
currentStamina = 0;
running = false;
}
}
else
{
speed = 25;
if (Time.time > lastSprintTime + delayStamina)
{
if (currentStamina < maxStamina) currentStamina += (replenStamina * Time.deltaTime);
}
}
}
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
why will this script not pick up when I press left shift?
What did the error say here?
#archived-code-general message
Did that get resolved?
Do you see the "yep" debug?
!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.
okay I know it doesnt want screenshots but I cant figure out the pasting code stuff so this is my code
I'm trying to make a stamina script that lets my player sprint for only a bit
It works right now, but the player can't unsprint, so im assuming the running variable isnt changing to false
what am I supposed to change in my code to get that to happen? when shift is not being pressed, do not sprint
this will never be false
it needs to be ==
running will never be false if you set running to true right before the check every single time
comparing it isnt working?
The comparison itself is fine, the logic is wrong
if you give me a cupcake and then ask if i have a cupcake, the answers always going to be yes
Just move everything but running=true out of the shift check
So if I understand you, yes
You literally paste your code at one of the websites, save it, and then post the link in the discord. It's not hard to figure out, especially, if you're asking for help in general coding channel instead of the beginner . . .
we ball
I'm not sure if this is where I should ask this, but is anyone using vs code for coding in Unity?
Yes they are
I was hoping someone could help me with getting it to work. No intellisense, no classes, nothing other than functions and variable types are coloured
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
I've done this, many times actually
You could try some of the extra steps I have on my site https://unity.huh.how/programming/ide-configuration/visual-studio-code-configuration
Still nothing
how about you give something more useful to go on, have you even attempted to debug or look around in the terminal for clues/errors ?
Show images of your package manager with the visual studio package,
And the unity extension in vs code
And I checked to make sure I had an SDK installed and I have 7.0.401
show console tab in Unity
Ok. Looks like a new package came out! Cool.
I believe you need the .net 4.something sdk
4.6 maybe?
Doesn't the C# dev kit only work with 7.0.x?
You can have 7.0 as well. You need the target framework for unity
Can I have both installed?
Regen Project files, re-open script . Look at Output tab in VSCode for errors
Yeah, you can have as many target frameworks as you want
I dunno which one it is, and I may be misremembering anyway. Sorry, I'll try to find a source
No errors
Looks like 4.8? https://docs.unity3d.com/Manual/dotnetProfileSupport.html
Unless this is the wrong place to look?
did you regen project files?
screenshot vscode
I did and all the terminal tabs are blank
Do I have to do anything with settings?
not really
Yeah I'm gonna go ahead and say I don't know what I'm talking about. I remember having to get a specific 4.something target framwork on my laptop like last year when setting up unity, but I don't remember exactly what that was abouy
I think .net sdk 4.7.1 was needed in the old way of getting it to work in unity and disabling modern .net basically
I've resorted to reinstalling everything
I would just use Visual Studio ๐
Vscode is good for webdev, c#/.net sucks on it
buggy mess, and they're phasing out VS for mac for this bs half assed extension
any one know how to rotate a float3 around a point using the unity's mathematics library?
Think about it this way: you know how to rotate around 0,0,0.
The point is your origin, you want your origin to be 0 so you can rotate.
So subtract the point from your float3, rotate, and then add it back
yeah i meant more the functions to use
since its different to the regular Quaternion functions you get with unity engine api
they have RotateX,RotateY,RotateZ and AngleAxis
subtraction, math.mul, and addition
it's pretty similar
mul instead of *
but which function do i need exactly ?
i presumed it was like this:
var rot = quaternion.RotateY(math.radians(angle));
var p = _a - _origin;
_a = _origin + math.rotate(rot, p);
mul
mul and rotate are identical operations (in this case), so what you have should work fine
@gleaming urchin do not spam/post memes, we have a dedicated channel, #archived-pricing-updates-talk for the actual discussion
!ban 744635215078621245 spamming
cartzz was banned.
!ban 526077902224228373 spam
unityplayersettings was banned.
been stuck on this for a while if anybody knows hot to fix it
i literally haven't touched my code since yesterday
woke up to this when it was working fine yesterday
Try this.
Close your project
In File Explorer Go to Library/ScriptAssemblies
Delete the 4 files starting with Assembly-CSharp
Open your project
You can safely delete the whole folder
These ones?
I tried to add incremental value on Y axis on UVS to make it bend/tilt the texture a little but it didnt?
for (int y = 0; y < yVertices; y++)
{
float totalX = xOffset;
for (int x = 0; x < xVertices; x++)
{
int currentIndex = y * xVertices + x;
incrementorY += 0.01f;
uvs[currentIndex] = new Vector2(totalX, incrementorY);
}
}
something like this
fr this chat ded now xD
What happened instead?
i dont understand whats frong?
FindObjectOfType returns a single object. are you sure you mean to be using that?
uhh, i was watching youtube tutorial:/
watch it harder and you might find your mistake(s)
not the same. look harder
solved, thanks๐
Hello! I want to modify the y value of the rigidbody speed by script, but it says that I can't bc it's not a variable, any suggestions? Thanks!
Thanks!
Uhh, so I am a little confused on how to create tiles for a tilemap in a script (I already have the sprites) as I could find no documentation nor video which showed how to do this
Hey, how should I write a script to make something bounce off a wall, with the same speed that it has when hitting the wall?
I have this thing
Vector3 _bouncedForward = new Vector3(_rb.velocity.normalized.x, 0, _rb.velocity.normalized.z);
modifier = 500f;
_rb.AddForceAtPosition(Vector3.Reflect(_bouncedForward, transform.forward) * _rb.velocity.magnitude * modifier, collision.GetContact(0).point, ForceMode.Impulse);
Debug.Log($"Boinked {collision.gameObject.name} with force = {(Vector3.Reflect(_bouncedForward, transform.forward) * _rb.velocity.magnitude * modifier).magnitude}");
The problem though, is that it doesn't bounce off with the same speed. I'm using the _bouncedForward vector to avoid changing Y-axis velocity, and adding the force at position, so that when the object hits the wall, it will bounce and also rotate a bit (like, a car hitting a bouncy wall would get pushed away at the hit point, therefore rotating a bit). Or maybe my thinking and idea are just not correct. Either way, what should I do to fix it?
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetTile.html
there's also the https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.GetTile.html method that you can use to just get the tile at that location and assign its sprite
Hey, I'm looking at adding sort of deadzone to collider based on separation distance being less than my deadzone value while keeping collision full response to collision forces with usage of contact api.
The problem I'm having is if any positive separation is applied the collision just gets ignored.
Any help?
Uhh, I tried to set up a tile map but nothing seems to happen, visually at least. Do I have to call a function like RenderTiles or smth once I'm finished adding the tiles in code?
I currently have this ```cs
Tile tile = new Tile();
tile.sprite = tileTexture;
tilemap.SetTile(new Vector3Int(x, y), tile);
Did you edit the tilemap?
What exactly did I have to edit?
I have the map
https://www.youtube.com/watch?v=ryISV_nH8qw
I lack the ability to explain this properly so I shall link this video from Brackeys, go to around 5:50?
Learn how to use the Tilemap tools in Unity to easily create cool 2D levels.
Watch TILESET in Photoshop: https://youtu.be/aaEEujLtsr8
โ Download Tileset: http://downloads.brackeys.com/tutorials/TilesetExample.psd
โ Extra Features: https://github.com/Unity-Technologies/2d-extras
โ Extra Examples: https://github.com/Unity-Technologies/2d-techde...
I'm doing this in code
I just give the code a texture and it creates a tile as shown here ^
Or do I still have to make a tile map like that?
Depends on what you're trying to do actually. Does those tiles require some sort of code? Like it's destructible or something?
Yes, it is supposed to be destructible, but I noticed something that could maybe be the reason this isn't working that I have rn
Ah, then I think it's another whole thing again.
Trying searching for Destructible Tilemap on Google
Oh yeah, I forgot to set a public variable mapSize in my code lol
Does it work now?
Yeah, but the character still trips so I guess I have to use the composite collider
Or I used to do this trick where I made the tilemap's collider a bit bigger
It kinda solved my issue
I would think since you need individual tiles to destroy, I think it's a better idea? I don't know you can try
So, it almost works, but (I have GenerationType set to Manual) when I call compositeCollider.GenerateGeometry() after adding all the tiles, nothing happens and I just fall through the tiles, but when I click "Regenerate Collider" in scene view, it works
Uhhh CompositeCollider2D
might be an issue
Why would that be? compositeCollider is just the name of the variable I have which is of type CompositeCollider2D
Oh yeah sorry about that I realized just now
Mind if we see the code instead?
Its kind of scattered throughout the functions, so I'll try to get rid of the unimportant things
hey guys, I'm trying to implement c# events into my game, and was wondering if I could add a string as a sort of selector for events? I.e. I want to have a collectible with a "collected" event invocation. What I want is to have something that subscribes to say, collect("coin") += function. is this possible to do?
private void SpawnMap(){
for(int x = 0; x < mapSize.x; x++){
for(int y = 0; y < mapSize.y; y++){
if(y == 0){ //Spawn grass
AddTileToMap(grass, x, y);
//Instantiate(grass, new Vector2(x, -y), Quaternion.identity, transform);
continue;
}
//Add other types of tiles
//...
}
}
compositeCollider.GenerateGeometry();
}
private void AddTileToMap(Sprite tileTexture, int x, int y){
Tile tile = (Tile) ScriptableObject.CreateInstance(typeof(Tile));
tile.sprite = tileTexture;
tilemap.SetTile(new Vector3Int(x, y), tile);
}
^
So the current situation is the map doesn't generate the collider at all right?
yes
after calling GenerateGeometry()
I'm suspecting that the tilemap collider isn't getting generated in the first place for composite collider to generate geometry
Odd that clicking "Regenerate Collider" in scene view helped then, but I can try to look into that
"When you add or remove Tiles on the Tilemap component, the Tilemap Collider 2D updates the Collider shapes during LateUpdate" https://docs.unity3d.com/Manual/class-TilemapCollider2D.html
This is most likely the issue isn't it?
This code is being ran in Start()
Yeah that should be the problem. Since tilemap collider wasn't generated, composite couldn't generate geometry
Guess I'm just gonna wait till' the next Update then
@rocky helm try this
If you require immediate changes to happen to the Collider, use Tilemaps.TilemapCollider2D.ProcessTilemapChanges to process them immediately.
It's on the documentation so it should work I think
Heya it works, thanks mate! Keeps the code much cleaner than waiting till' the next Update too!
Hi do you guys use namespaces in your own code and to folder-level depth or more shallow like MyMathsLib, MyUtils or Company.Utils?
I personally do, especially if working with others as that helps prevent accidental name collisions. it's also just kind of good practice in general. but how you do so and even whether you do so is personal preference. just do what makes sense for your project tbh
hey guys, how would I implement something like this with c# events? ```
collectible class ---
public event Action CollectItem(string????)
triggerenter()
{
CollectItem("coin").invoke;
}
other class ---
wait until "coin" collected event is called.
CollectItem("coin")+= Func;
sorry if it sounds like utter madness, just trying to figure it out
c# events or Unity events with inspector support?
Unity events with one parameter: https://docs.unity3d.com/ScriptReference/Events.UnityEvent_1.html
c# events: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
I have a code question! I want to use one script to activate an object it is not attached to script (flip it from on to off). what is the best way to go about this?
Make object a variable in the script, attach said script to another object, assign target object to the script, then control the on / off from there.
What have you tried?
Create a reference to the object from your script.
Activate/deactivate as necessary
lol those generals are things I already know but thank you. I am more looking for the wording.. I'm stuck on what to write it as in the code.
Elaborate? I don't get what you mean by wording
you mean like .setActive(true) / false?
yes. I'm having trouble targetting the script on the object
Break down the problem. What's the exact issue?
how do I target the component of the object to set it to true?
Ohhhhh
gameobject.getcomponent().setactive(), something like that
thanks!
this.GetComponent<BoxCollider>().enabled = true; / false
my bad, it's like this, can't rmb off the bat
I am getting an error about the targeted script. saying it is not valid to target. I think I did something wrong
oh wait
I forgot to attach the object to the script LOL
most common error in programming.. forgetting an obvious step when the code is fine but a linking of some kind was forgotten
I have a 100 x 100 mesh that looks like this originally,
when thesame mesh is rendered with my instance shader, it looks like this .. notice the extra deviations in color
there is nothing in the code that would suggest this change
size as in data size?
ye
Your json is a local file or what it's the situation there?
Iโm making a 2D TopDown game in which the character has the ability to dash. But when I dash the character can get stuck in another object that has a rigidbody2d. How can I make the character stop when he collides with an object?
Here is functions to dash and to move, also video of issue:
No I have a json formatted string, I want to know how much size it is going to be.
PlayerPrefs.SetString has 2KB limit, I want to know how close I am
Under C# I rmb there's a get byte count function for strings. You can try to google that
just use string.Length
I tried but its wants byte to be inputted? not sure how that works
isn't that just character counts
well that is what you want for playerprefs.setstring isn't it?
the PlayerPrefs.SetString docs says it has 2KB of limit, I want to know how close my current string/json is to that limit
I'm not sure, thats why I'm asking here lol
It's a string, if they set a limit it will be in length of string
in that case , how do i find out if my length is close / or how far its from limit?
2kb - string.Length
or if you are worried
2048 - Encoding.UTF8.GetBytes(string).Length
try this
int datasize = System.Text.ASCIIEncoding.Unicode.GetByteCount(mystring);
Debug.Log(datasize);
Debug.Log(mystring.Length);
Should be what you're looking for
nobody stores in Ascii anymore
Then change to whatever encoding spaget needs
It's an example anyway
is it better to get an audioclip from a list or using Resources.load?
list
as in a list set up in a prefab
yes, they will load at startup
Your raycasthit2D should contain a field called "centroid", try assigning your object to that position
(When a collision is detected)
are you saying resources.load could cause the game to briefly stop when used?
thanks ! @knotty sun & @karmic patio
stop, no. Lag, yes
havent noticed anything so far
i use it to add the specified clip to an audiosource that gets destroyed when its done playing
even worse, you are adding garbage collection to loading, 2 hits for the price of one
would it help if i unloaded it afterwards?
there are a lot of factors to consider, size, frequency, target platform, target spec
its for sound effects if that makes anything clearer
not really no, although I guess it makes the size quite small
general rule, load at startup dispose at end of game. Unless you have a pressing need to do otherwise
so just making sure, its better use a list set in a prefab per-object?
yes
thanks, guess thats a bit of code ill need to rewrite
i gave a gameobject the button component and still cant click it
Hi, I have a question about a bug with some Vector3 and input and I struggle with it until this morning and I really need help : I have a normal c# script that make my player move with ZQSD but when I release any key, my player continue to move after during a short time. My script was working well before this morning...
Where are you sampling input in your code, and where are you applying movement?
That's my script
player.Hard is the RigidBody of my player
anyone?
Error says moving the file failed and that the file already exists at the destination.
So adding force will give the player momentum, which needs to be reduced somehow. It's like pushing a hockey puck, it'll keep sliding around unless there's something to slow it. You can increase the mass and make sure the surface it's on has friction
i figured, now idk which file its referring to and what script to modify to stop that.
Ok I will try, but idk why but my player before this morning have is speed reduce quicker
What's the line at the bottom of the screenshot for?
As opposed to the one inside the if
In this line of code I add a force which is the inversion of the current velocity of the player, multiply by the maximum force to move the player divide itself by the maximum desired speed, all multiplied by a value allowing this effect to be reduced when I want it (playerGlis variable)
What's the intent, I mean
The if is for stopping to add force to my player when I open the menu
Is to reduce the player force that I add to him, by using the same force, multiply by all the the thing that I have say above
Ah so it's aimed to be a sorta speed limit?
Yeah and to prevent him from slipping
(I need to go to lunch now but can I come again in like 40/30 min to continue?)
I'll be busy around then but I'll think on it, maybe someone else can spot the issue in the mean time
Might be worth to look up references to the player rigidbody to check for any sneaky things happening elsewhere
Okkay thanks again ^^
I'll think about it
How does SpriteRenderer scale the texture?
I am trying to add support to PC users with keyboard using the new input system using the Send Messages behavior
The joystick for android support work perfectly but the keyboard doesnt...
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player_Movement : MonoBehaviour
{
public float horizontal;
public float vertical;
private Rigidbody2D rb;
public Joystick joyStick;
[SerializeField] private float speed = 0f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
// FOR ANDROID SUPPORT
//Move Right And Left
horizontal = joyStick.Horizontal;
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
//Move Up And Down
vertical = joyStick.Vertical;
rb.velocity = new Vector2(rb.velocity.x, vertical * speed);
}
//FOR PC SUPPORT
private void OnMovement(InputValue inputValue)
{
rb.velocity = inputValue.Get<Vector2>() * speed;
}
}
It works. Is it correct way to do it or can it be done better?
return _currItem ? (_currItem.GetComponent<ItemController>().collisions & ItemType.Empty) == 0 : false;
I am making a Singleton instance of a Canvas GO, which contains a map and all it's special procedural data. I need to save this data between scenes and ideally just load it again next time I revisit the original scene. The camera breaks once it is reloaded into the original scene. In this case, should I make my Main Camera a Singleton as well? This way it stays in DDOL space, and the Singleton Map can continue referencing it
Update: Yes, it appears that just adding in a MapCamera Singleton as well fixes the issue. One thing I had to make sure of was to remove the Main Camera tag on that MapCamera instance so it doesn't interfere with the Main Camera of the new scenes when they load. Then they both persist through all scenes, and on the original scene reload, they work. Hooray!
<@&502884371011731486>
Any idea from what can cause this trouble ?
What is the correct version of .NET I should be using? vs code is being stubborn and not using 2.1.30
which Unity version?
hey guys, I was wondering how to use a c# event without getting a ref to the class/object invoking it? I tried declaring it as static but that won't work
Latest LTS
from what I can Unity uses .Net Standard 2.1.0 or .Net Framework 4.7.1
Thanks, I was able to get it to load in but intellesense is still borked. I followed the vs code instructions in !.ide but still nothing
Static events work fine, but know that you won't be able to have two objects with their own event handlers, and invoking one out of the others when you have multiple instances.
Just use the type name instead of an instance of that type when dealing with the event, like other static stuff
so instead of ```
Item itemRef = ref
itemRef.event += Function
I'd do
Item.event += Function
For a static event yes
when I try to use it via type in other classes it doesn't let me. here's all the relevant code to my event ```CS
public class CollectibleArgs
{
public CollectibleArgs(string name) { Name = name; }
public string Name { get; }
}
public class Collectible : MonoBehaviour
{
public delegate void CollectEventHandler(object sender, CollectibleArgs args);
public static event CollectEventHandler OnCollectEvent;
....
that's not inside of a method
was able to fix by clicking "open cs project" in the assets submenu. quite the odd bug
Event subscriptions are statements, as such they must be in a method like other statements. Try in Awake or OnEnable
And unsubscribe in OnDestroy or OnDisable, respectively
yeah I forgot about that haha, thanks
I need this button to call a function in a script in it's parent. I can't figure out how to drag the parent script into the button target.
oh nvm I had to switch to scene lol
Frozen is never true but ฤฑdk why
anyone know what this error means?: MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
It happens after my friendly AI 'destroys' an enemy AI it was targeting
That error is clear as day, what part do you not specifically understand? It even tells you what you should do
Isnโt clear to me. There is no reason destroying one object should crash the game so what it is saying makes no sense to me
You are destroying an object then trying to use it
'but you are still trying to access it'
you will crash the program accessing something that no longer exists
I assume when the enemy is destroyed, your AI is still attempting to target it. You should null check it and then if it no longer exists, have the AI do idle stuff
Hey Hello there. I got a Question about setting the MouseCursor in unity. I found that Unity directly does not Support that but still with using System.Runtime.InterlopServices you can Use SetCursorPos and it actually sets your hardware cursor. My Question would be how to actually Handle having multiple Monitors or Windowed Mode (because as far as i've tested 0/0 is the bottom left of your Game window. If someone has the Windowed Mode on and Moves the cursor position and then loads it it differs from the actual saved position.)
I would look for someone who could help me on this matter or might propose a different solution for me to set my cursor (for context i want to be able to pan my camera by holding right click (while the cursor disappears and then when i let go of rightclick the cursor should appear where i left it))
and apparently I wrote the null wrong because it keeps happening so I need to know a code that handles that. the error did not change so I've done something wrong ๐ฆ
you can check if an object is null or destroyed by comparing it to null with the equality operator
It may help for you to show what you've done if what boxfriend said doesn't do it for you (but it should)
if(enemy == null)
{
Patrol();
}
you should probably share the entire class. !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.
Hey guys, sorry if it's the wrong channel but I just joined this discord.
I'm currently working on my first game ever and I'm using a Circle 2D Collider to check for object in a range around the player in order to interact with them.
I've set the object to trigger but it's still colliding with every other collider (that is not a trigger) in the scene. Any idea on how I can fix this ?
Without the said collider
i recommend using a physics query like a Physics2D.OverlapCircle instead of a circle collider and relying on physics messages
Oh thanks a lot for the quick response ! I'll try that
So I tried experimenting for a bit, the problem is that I'm following a tutorial and I don't really understand everything yet. What I'm using is a script that uses a list of all the objects that have the interface IInteractable and that are in range. I think I managed to the Collider2D of an object that is in range, however, I don't know how to get if that object has the said interface. Can you nudge me in the good direction please ?
TryGetComponent
I played around a bit and managed to get it working !
Hi all, I am looking for some pointers on how to make a certain game mechanic.
I am trying to acheive an effect similar to that in 'Evil Genius 2' where the base building occurs underground and as you build rooms the area gets mined out.
I was thinking something like a tilemap, that when you place a room, the tilemap removes tiles in that area?
That sounds reasonable.
How do i implement this? i want the character to swing in the direction of horizontal key pressed...to me the problem is how do i rotate the character in specific direction holding that stuff?(image is from PoP The Lost Crown)
maybe rigidbody + a hinge/ joint , then add more torque the longer you hold
Thanks, I'll try it
anyway to get a TMP_SpriteAsset from an AssetBundle? I figure that when loaded it'll only reference the relative location of the required assets (material, sprites), so is there a way to do this such that I can keep the material and sprites associated with the spriteasset?
I found this https://forum.unity.com/threads/sprite-asset-from-asset-bundle.794388/ but assets won't stick
How would I check if an object is within the collision bounds on another object within the script of a third object in which none of of the objects are childs/parents of one-another?
Could do one of the overlap methods using the objects position as the overlap position
But I guess you would have to constantly poll that
Otherwise have the object invoke an event that you can subscribe to
thanks
Any youtube videos that you guys recommend to watch to learn unity?
pinned messages from #๐ปโcode-beginner
how do you properly save generated meshes in prefabs ?
in edit
i create them and assign but they dont visibly show up unless i select the gameobject
very strange behaviour
You can't
You have to create an asset
how come it doesnt make assets of meshes when we create prefabs with meshes already on them
kinda strange we have to turn them into assets
Just like how you can't reference scene object from prefab
Meshes you created is not persistent unless you make it into asset
so what does it do when you drag a gameobject and make it a prefab
because that seems to work fine
its only when i generate meshes via code it fails
Dragging what gameobject
from the scene
if you make a gameobject in scene and add a generated mesh then drag it to make it a prefab it works fine and the mesh didnt have to be saved as an asset
but if i generate a new Mesh() and assign it to the prefab asset object (via code) the behaviour is different
Either way wouldn't work after you restart the editor
hmm i see
maybe i'll just store the data and just generate the mesh from the persistant data
saving tons of procedural mesh asset files seems like a terrible idea
Sure that's fine too
its weird because it does save the mesh even if i restart unity
but it just wont show it unless i click the object
very odd
What does mesh field from inspector look like
thing is when i click to look at the mesh inspector, it then shows the mesh so i cant see what the inspector looks like when its not showing the mesh lol
its fine though, i'll just do a redesign
So you can see that it says (Instance) which means it is temporary
I assume that something is triggering to regenerate when you click it
yeah im trying to understand how i would keep track of the meshes if i saved them as assets
given its procedurally generated
i dont know an easy way to keep track for when i want to wipe and regenerate the mesh again
You can do AssetDatabase.AddObjectToAsset and put multiple meshes in single asset
how would i generate and keep track of the first asset though
With path convention? Idk, that's just up to you
.
tried the plateup modding trick of adding it to fallback assets, copying the default asset's material and setting the texture but didn't work
this is quite unfortunate
Is anyone else able to get Visual Studio 2022 to output PDB files on a release build? I'm trying to follow these instructions: https://docs.unity.com/ugs/manual/cloud-diagnostics-advanced/manual/DebugSymbols
But no matter which route I try, there is no Project Properties page that comes up in Visual Studio. I've seen screenshots of what the windows is supposed to look like, but all I get is this small window with almost no options.
Build settings with Development Build enabled would probably get PDB files I would think, I don't expect a release build to ever have PDB files. Just a guess though, never done debugging like that, I just debug the Development Build.
Don't know what kind of project that is but it doesn't look like a Unity project
It's an assembly in a Unity project.
screenshot your Solution Explorer
I think it must be something to do with the way Unity Generates csproj files, I can't get properties up on their projects either
I wondered if it was something like that. Tried deleting all the csproj files, etc, but this is all I ever get. Seems odd that this is on the Unity docs, but they don't seem to support it.
I think it is outputting pdb filles. They seem to be going into the Temp/bin/Release folder
Hmm, mine's empty, maybe it got tidied. Let me try another build...
No, still empty. I had "Copy PDB files" checked as well, which does seem to produce a PDB for UnityPlayer.dll, but not for any of the dlls made from the assemblies, which I guess is what I really need.
guys i need help with my screenshot script, apparently my screenshot output is darker than my original sprite texture. ```private void OnPostRender(){
if (takeScreenshotOnNextFrame){
takeScreenshotOnNextFrame = false;
RenderTexture renderTexture = myCamera.targetTexture;
Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
renderResult.ReadPixels(rect, 0, 0);
byte[] byteArray = renderResult.EncodeToPNG();
filePath = Application.dataPath + "/CameraScreenshot"+ System.DateTime.Now.ToString("yy-MM-dd") +".png";
System.IO.File.WriteAllBytes(filePath, byteArray);
Debug.Log("Saved CameraScreenshot.png");
RenderTexture.ReleaseTemporary(renderTexture);
myCamera.targetTexture = null;
myCamera.enabled = false;
}
}
private void TakeScreenshot(int width, int height){
myCamera.targetTexture = RenderTexture.GetTemporary(width, height,16);
takeScreenshotOnNextFrame = true;
myCamera.enabled = true;
}
public static void TakeScreenshot_Static(int width, int height){
instance.TakeScreenshot(width, height);
}```
this is the image before screenshot
this is the screenshot output
This looks like gamma/linear conversion issue. You might be able to fix it by creating a texture of the right format, for example passing true for the linear parameter in the renderResult constructor.
Otherwise, you can correct the pixel colors manually by converting it either from gamma to linear or linear to gamma.
so how do i do that?
is it by code or unity inspector?
As I said, you could try passing in true for the linear parameter in the renderResult constructor. Now you're passing in false.
If that doesn't work, you can try correcting the pixels manually as you have tried before. Except gamma isn't just a multiplier, it's a power, so the correction is Mathf.Pow(color, 2.2f), but Unity's Color type also has properties to convert between gamma and linear.
as in change to true? i tried before, result is the same Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, true);
So then you can try doing the gamma conversion manually as I described.
still have no idea what are you talking about, nvm thanks for your reply
might be due to TextureFormat as someone mentioned at #archived-code-advanced still have no idea what it means
gonna try asking around at #๐ปโcode-beginner maybe my coding level is not that high to understand, sigh
you are allowed to go and read the Unity docs, you know
ya, reading through the difference of TextureFormat.RGB24 and TextureFormat.ARGB32 as i ask around
Also Linear and Gamma space
i need answers and online materials are not giving, hence im here
btw did you compare the colours on the original texture and the saved one to see if they are different because it could just be the program that you are using to view the saved screenshot
so far i tried increasing the brightness and it worked but, not similar to my original image float brightnessFactor = 1.5f; Color[] pixels = renderResult.GetPixels(); for (int i = 0; i < pixels.Length; i++) { pixels[i] *= brightnessFactor; // Apply brightness adjustment } renderResult.SetPixels(pixels); renderResult.Apply();
how do i do that?
loop through the bytes on each of them to see if they are the same
in the code?
how else?
but how do i loop the byte and check in code?
ya but what will i be looking for inside the byte? never tried debug.log on a byte before
who said anything about debug.log?
sigh i give up, im going back the documentation reading and googling
I would suggest a C# course
I'm not sure this is necessarily the way to go here - the screenshots look to be different sizes, so you won't get a pixel-by-pixel match anyway if that's the case.
thx, looks slightly clearer now, now i just need to figure out how to make it exactly similar as original
Anyone have any code for hit feedback? (Damage amount, SFX etc.)
If(hit)
{
DoDamage(damageAmount);
PlaySFX(sfx.damage);
}```
Sorry, I should clarify, I meant some text popping up near where the object was hit, showing how much damage was done, and then fading away or something.
in that case you need
if(hit)
{
DoDamage(damageAmount);
PlaySFX(sfx.damage);
TextPopup(damageAmount);
}
You'll be taking advantage of 3D/2D text and instantiating it in the scene where the creature that was hit.
Ok, thanks!
As I said, if this is a gamma/linear issue, which it appears to be, it's not enough to just multiply by a constant. Gamma is not a linear curve, so the brightness difference can not be reversed with a single multiplication. The right correction would be to raise each color channel to the power of 2.2. But an easier method is to use the gamma and linear properties of Color, like is shown here:
https://forum.unity.com/threads/texture2d-encodetopng-output-way-too-dark-does-not-apply-gamma.1468631/
But as they explain, doing this on the CPU is slow, so it's best to ensure all your textures are in the proper format to begin with.
Guys I have a question, I want to make a lootbox and inventory systems, but I don't know how to do it.
For the inventory I could just use a list and I add some objects when I obtain them, but how can I check if I already have a certain object in a list, so I can decide which objects should the player get when he opens a lootbox
Simply iterate through your list
My weapon is too large scale on pickup its not wokring to pickup it
pls help me
Don't cross post
and there they go crossposting again <@&502884371011731486>
@west mesa You've already been muted before for spamming your questions across this server. What part of all of that are you struggling to understand, so we can make it clearer.
I need help to make the player aim right in unity
Stick with one channel #๐ปโcode-beginner message
I'm trying to use AddTorque to make a beeble, how do I get the axis around which I should be adding the torque?
Basically I want the vector that is rotated around between Quaternion.identity and rb.rotation
It works in the current scene. If you mean for additive loading, I don't know
add a parent object as root for the objects you want to find
Hi. Does anyone know if it's possible to create events at runtime with specific names and add listeners to those events based on its names please?
I have this but it just runs away for some reason.cs rb.AddTorque(transform.eulerAngles - transform.up);
Vector3 AxisYouWantToRotateAround = new();
float rotationSpeed = 1f;
rb.AddTorque(AxisYouWantToRotateAround * rotationSpeed);
you should find the axis first
That's the problem, I don't know how to find the axis I want to rotate around. it should be perpendicular to both transform.up and transform.eulerAngles.
whats the use case
like, a level editor to be able to create custom events such as "when player enters certain Collider Trigger, trigger event named "playerInsideRoom" "
idk if I'm explaining myself
you could use refelction to get methodinfo then invoke it,but i dont think thats the right way,
the user is using editor or thats a runtime thing?
if its a in-game editor,you should predefined everything instead of using some string to find your event
so then I should create for example 10 different events and let the player decide when those are invoked and for what...?
hey guys I need to create a json file for character dialogue, I have the dialogue in a text file already but someone said to use json file instead can I just use this site?? https://jsoneditoronline.org/
JSON Editor Online is a web-based tool to view, edit, format, repair, compare, query, transform, validate, and share your JSON data.
Is FixedUpdate called before, after, or varying relatively to the physics calculations?
yes,but there is some design pattern to avoid rewrting same code,but string is a very bad idea
Physics calculations run at the same cadence as fixed update
FixedUpdate is for physics
I want to know if I can rely on physics being done before or after my FixedUpdate
It is done at the same time.
Neither before or after
There is nothing done at the same time in 1 threaded code
maybe a debugger can help you
Fair. Looks like after from that image. I dunno. I just know it is linked to fixed update
Answer from a Unity stuff on the official forum:
"Typically applying things like forces are done in the script FixedUpdate because physics runs immediately after the scripts are called."
yes ,if you call rb.AddForce in your fixedupdate, it will be update your rigidbody in exact same frame
I think you messed up the terms but I understand. Thx
Hello I dont know where to ask this questions, but does anyone know how do I solve this error:
"Task :unityLibrary:compileReleaseJavaWithJavac FAILED"
I am trying to make an android application and i keep on getting errors... any help?
Post the full error message in #๐ฑโmobile
oh ok thanks
When particle system doesn't emit any more particles does it Stop or Pause?
Hello! I'm stuck with a build problem. The game in the editor works fine, but when I run the build the game freezes after generating the world. It freezes right after all the objects are spawned, and the most weird thing is that it only freezes when I use this line:
save.newWorld = false; (line 109)
save is a non-null GameSave object, which is simply a class that holds some data. The saveWrld variable is used only three times in the whole project, one is an "if" right above the code that I posted, and the other two are the row 109 in the screen and in the GameSave constructor.
I have absolutely no clue why setting a value to a boolean variable should make thhe game completely freeze, without generating exceptions.. While in the editor it works flawless. What can I do to debut it? I really found nothing online; the debugger runs until the game freezes in no particular point... And I can't find what's making it crash. The project is not very small...
The profiler also freezes, as if the game was stuck in some infinite loop.
if it's stuck in an actual infinite loop in C# code somewhere, you can often still attach the debugger and hit pause to find out where even if the editor UI is frozen
It says that it's stopped in an unreachable code..
Nevermind, I fixed that problem. Seems like even if max quality build was the default quality setting, it still started with a different one. Disabled all the other quality settings worked.
My profiler shows that the editor takes 8ms. Will my game really take 8ms less in release?
it stops
only if u share ur .scene file instead of .exe
???
You can launch a game with a .scene file??
no, but you can launch editor
So if in profiler my game takes 11ms of which 8ms are editor then in release it will take only 3ms?
if your resolution is going to be the same of the editor then most likely yes
you can google some simple ways to create FPS tool that will show you your actual performance after you make a build
Will frame time differ from what Profiler shows under PlayerLoop?
probably because u will have more resources available
RAM?
just about everything that unity uses for its editor
So things like cache too
everything related to performance pretty much, i sometimes get hardly 30 fps on my game im doing atm but in build i easily hit 120-150fps
I think you should try to profile on the phone with a special tool. Likely because of different limitations and architecture it has some weak sides you didn't think about.
for phone profiling u just connect unity to phone, and do some steps to have it shown in profiler, its pretty sweet
u could use special tools i guess, but unity has pretty decent way of dealing with developing games for phone
I just didn't know that one existed
ik
i just added the admob package. it builds fine in unity. but in vs2022 it does not seem to recognise it. any idea what i can do?
tyvm
Is there a way to change audio volume on import? Changing sample data inside AssetPostprocessor.OnPostprocessAudio has no effect
If it's a setting on the Asset Importer,
then you can use the Edit > Project Settings > Preset Manager
and create a Default Preset for that asset type.
All new assets will then have those preset settings, when they are imported
No it's not unfortunately
Anyone play Cyberhook? The game has a level editor, but the way it works is that it opens up some sort of lite version of the Unity editor with preset assets that you can modify. Anyone know how that's done?
does anybody know why this doesnt work?
the agent is the square and the sphere is the target
im using ml agents btw
doesnt what work?
its been loading for this long
it wont let me exit
and the ai is not able to move the square
seems some module is missing
well ye onnx let me install rq
but the ai like stretches the cube instead of moving it
not sure how its supposed to work if its missing the model
the module just saves the ai into a file but you can still train
and what do i do with this?
oh nvm it loaded
but why does it stretch the cube?
does it have to do with these?
are you also rotating it?
no
hmm maybe a short video would help see the problem
it doesnt even try to move i think i am doing something wrong with the movement
not sure. you could try asking in #archived-machine-learning
you can try showing the Code too
.
does anyone have a script where a bullet kills a enemy i really need it rn
what are the enemys in your game
are they physical objects or can they go thru solid objects.
do you want the bullet to cause the enemy to die. or should the enemy die when reacting to the bullet.
OnCollisionEnter(Collision other)
if (other.gameObject.TryGetComponent(out Enemy enemy))
enemy.Die()
you need to post your !code correctly . . .
๐ 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.
you can easily find videos online. we don't just post or hand out code . . .
Sounds like you're in a wrong channel.
Hey just a code architecture question. So I have many AI controlled entities that need to execute "tasks". Imagine if the overall objective was to build a bridge, the unit would...
- Find a pile of wood.
- Carry it to the build site of the bridge.
- Add it to the bridge.
- Find another pile of wood.
Sometimes though a task could be as simple as "follow this guy".
I would like it if tasks were able to be interrupted or resumed as well. Like if an entity's current task was "patrol this area", but it was suddenly given a new task to follow a unit for a minute. It would return to patrolling that area when time was up.
Is there any existing architecture that suits these needs? I am aware of behaviour trees but I don't know if they're the best match for this?
You could look into finite-state machines, but they could be a little overkill for what you are doing right now
I would assume that a state machine could be implemented "a layer down"? Like a single task could have a state machine and involve lots of state changes and thinking.
Or, maybe you can just set a state for each of the AIs and have a "main script" of some sort make the npcs execute tasks depending on the state, if the AI needs to be really simple
Well in my case what's giving me trouble is that outside entities need to tell my units where to go and what to do.
So it's less that I set up a specific AI with a set of tasks and behaviours on start.
And more like my AI yells out to surrounding things asking "what do I do?"
And gets told "do this" or "do that".
I guess imagine like... Pikmin? You throw them and then they try to figure out what they should be interacting with.
And what they do HIGHLY depends on what's around them.
They could go fight, they could go hit a wall, they could go pick up an object, dig a hole etc etc.
I guess I could write all these cases, but it makes sense for the unit to just ask nearby interactables what they should be doing.
Maybe?
So question about the generic collection pooling stuff that was added in the last few major versions. (ListPool, DictionaryPool, etc.)
What happens if I pull from ListPool<int>, add 8 billion ints to the pool, then release it back to the pool? It gets cleared on release, but adding all of those elements would have internally allocated / resized a collection within the list. When I return it to the pool, does that stay in memory forever, or does the API do "branch trimming" of outliers like this?
hey, not too sure where to ask this. is there a way to tie each animation to a material then apply that material using some native functionality, or will I need to do that in script?
A material? Uuuh maybe within the animation itself you can access the Renderer and set a material there on keyframe 0? No idea if it can do that though.
Hello, i create dictionary during runtime, and fill it, and save it in prefab
A the end i do this:
EditorUtility.SetDirty(gameObject);
AssetDatabase.SaveAssets();
and the dict is [SerializeField]
but when i press START the spawned prefab's dictionary is null
Thanks I'll investigate
Maybe worth just switching out based on speed since I know what speed animation will change at anyway
I just opened unity today and trying to open script using visual studio. But it throws an error, what does it mean?
D:\Documents\Unity\Nightmare Side The Game\Assembly-CSharp.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\TechniePhysicsCreatorEditor.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\Assembly-CSharp-Editor.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\TechniePhysicsCreator.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\Assembly-CSharp-firstpass.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\NewAssembly.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
D:\Documents\Unity\Nightmare Side The Game\Technie.PhysicsCreator.Updater.csproj : error : Expected 1 export(s) with contract name "Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace" but found 0 after applying applicable constraints.
i've added GoogleMobileAds to my game. and it works fine in unity. however when i try to create an android build i keep getting errors. Assets\GoogleMobileAds\Editor\BuildPreProcessor.cs(5,19): error CS0234: The type or namespace name 'Build' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) this is one of them. but i get like 10 or something like that all from GoogleMobileAds.
Perhaps you can reassign vs to be the external code editor and make sure you have the latest vs package, but if that doesn't help then I don't really know
So im trying to draw a sphere and box collider inside a transform object this gives the object a local position but how can i solve that?
first off, you don't need to use GetType and then manually cast to type check and cast to the correct type. you can use the is operator to do both
if(collider is BoxCollider boxCollider) will check if it is that type then cast it to the type and store the result in the boxCollider local variable.
also you should use the explicit type Transform for your foreach loop so you don't have to cast on literally the next line. and you should also consider using TryGetComponent instead of GetComponent and then not null checking. what happens if one of the objects does not have that component? you suddenly get a NullReferenceException and the method does not continue
as for the issue you are actually experiencing, since the center is in local space you'd want to use something like transform.TransformPoint to convert it from local space to world space
but how does TransformPoint work?
did you look at the docs?
yes, that is how you use that method there
i dont get why i need to give a parameter while i just want to convert it to global
you have to tell it what point you want to convert to a world space position. so you pass the local space point you want to give it as an argument for the method call
you may also need to use the TransformVector method for the size as well if the collider's parent scale is not 1,1,1
i was always confused about the transformpoint
aa i get it
but my parent scale is always 1,1,1
but thank you very much
aa and the transform you use to call this function is ofcourse the parent
i figure it out
aa
i've added GoogleMobileAds to my game. and it works fine in unity. however when i try to create an android build i keep getting errors. Assets\GoogleMobileAds\Editor\BuildPreProcessor.cs(5,19): error CS0234: The type or namespace name 'Build' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) this is one of them. but i get like 10 or something like that all from GoogleMobileAds.
Not really a coding question and more of a build question. Try #๐ฑโmobile or #๐ปโunity-talk
Hello guys, can you please suggest me a way to implement hingejoint system for character controller component?
is there any way to do Physics2D.OverlapBox for all the layer masks, except one?
i know there is a way to make detect only some layer masks exclusively, but is there a way to detect all but one?
so i should i jsut like, all the layer masks but one?
i did consider that, but i thought there might be a better way to do that
the only other way to do it is to just select the one layer in your layer mask then invert it. but it's still basically the same exact thing
also you should keep in mind that the individual layers are not themselves layer masks
!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.
Thank you
Hello,
Visual Studio can't seem to communicate classes that i created, even though i set thing as public static. Or function like Time.timescale as exemple there is no special color or anything about it. May someone have an answer please ?
The instructions are literally two messages above yours
Ikr, pretty sure i did install Game dev with unity when i installed it first
Is there a way to check that ?
Go through the configuration again, you'll see if it's there
there are also other steps
Ok, thanks
Got already install, but miss few step, seems to work now, thank you !
hello, slightly weird question but is there any way i can detect if a player sets their windows display orientation to be flipped?
these are only for mobile, im looking to check for windows pc
it says its only relevant for mobile platforms in the docs annoyingly
Maybe you can check if Screen.height is larger than Screen.width? ๐ค
Not sure if that accomplishes what you need tho
not quite, the height and width stays the same
i imagine this is an incredibly niche requirement so i wouldnt be surprised if theres no way to do it
Input.deviceOrientation seems to be the same
if it's a niche windows only thing you likely will need to use a native plugin to get this info
i.e. you write some C code using the Windows API to get the data and call that code from your Unity code
oooo interesting okay this looks fun, thanks
Can you call Physics.OverlapSphere on multiple threads or can it only be accessed on the Unity thread?
So, i have this problem with my attack system.
Every entity in my game have some attacks. Every attack have an action points cost, some other variables and an effect. The effects can be very variable and can modify a lot of things so i use a method Effect() for coding this.
But...the effect is different for every attack of every enemy.
How can i treat the attack as an ogject (like a struct or a class for example) that i can give at my entity without creating a class for EVERY attack in the game? Cause the Effect() method is always different...
use an interface
But i still have to code every Effect(). Can i give at the Enemy the interface and give him more then 1 attacks?
Only on the main thread
yes of course you do, you said the Effect method is always different
You can do overlap sphere in the job system via https://docs.unity3d.com/ScriptReference/OverlapSphereCommand.html
Or i should do a class Attack with the interface into it, and add the attacks in the enemy creating the attacks with scripting?
that is up to how you design it
So... i can give an interface with Effect() at the enemy, and that enemy can have more then 1 Effect() into his code?
Ok that's new for me
Can anyone help me figure out why my code is giving a NullReferenceException on the line childrenList.Add(obj)? if I change List<GameObject> childrenList to public the error stops, but it's not functioning as intended and I'm not sure why
public class Projection : MonoBehaviour {
[SerializeField] private GameObject projection;
List<GameObject> childrenList;
void Start() {
Debug.Log("Projection Layer: " + LayerMask.NameToLayer("2D Projector"));
//projection = new GameObject(gameObject.name + ".2DProjection");
getChildren(gameObject);
string output = "Children:\n";
int i = 0;
foreach (GameObject obj in childrenList) {
output += $"{i}: {obj.name}\n";
i++;
}
Debug.Log(output);
}
private void getChildren(GameObject obj) {
Debug.Log($"Child: {obj.name}, Layer: {obj.layer}, Layer Name: {LayerMask.LayerToName(obj.layer)}");
if (obj.layer == LayerMask.NameToLayer("2D Projector")) {
Debug.Log($"---- Projector found: " + obj.name);
childrenList.Add(obj);
}
foreach (Transform child in obj.transform) {
getChildren(child.gameObject);
}
}
}```
because childrenList is null
omg I forgot to initialize it I definitely need more sleep
When the list is not serialized, the inspector doesn't create the list automatically so you have to do it yourself.
thanks! ๐ฆ
How do I get the touch.fingerID from eventData.pointerId?
Apparently these IDs are not the same
Is there a noticable difference if I had ScriptA on 50 (simple) npcs or if I were to keep the npcs in a list and loop through them whenever an action needs to be done. For example if (objectB is close enough to npcs[i]) ... rather than if (objectB is close enough to transform) ... in all 50 npcs (Obviously there is gonna be more that they do, but this gets the point through and they stay rather simple)