#archived-code-general
1 messages ยท Page 104 of 1
OK, I think I'm just stupid at this point :
writing PhysicsScene2D.defaultPhysicsScene gives me an error : PhysicsScene2D does not containt a definition for defaultPhysicsScene.
It's Physics2D.defaultPhysicsScene
pay attention to what you're copying ๐
yeah, I'm getting frustrated with these raycasts.. I need to take a break and breathe a little ๐
Hi. One question, does anyone know if there's a way to like interact with something based on where the mouse is?
Like, I want to interact with a 3D button inside an aircraft cockpit. I was currently using a physics raycast, and that worked fine when the aircraft wasn't moving, but when it starts to move, the raycast just doesn't hit anymore, like as if it was lacking behind. Any idea how could I solve that please?๐
Use the event system rather than manual raycasts
e.g. IPointerEnterHandler / IPointerClickHandler etc.
also do note that all of this raycasting stuff is based on physics colliders, and physics collider positions only update during physics simulation frames (which is not every frame)
Oh okay, I've never used that, I'll do some research about it thanks for saying that ๐
unless you use Physics.SyncTransforms before the raycast to force it to update
it can be behind
but even if I shoot the raycast on FixedUpdate?
It doesn't matter - if you've moved the objects in Update then the visual appearance of the object can be ahead of the collider
well the object doesn't move other than being a child of the aircraft itself, but the same happens with the camera, so I thought they would be synced
and the aircraft moves... in Update?
if so ^^^
well it is using a rigidbody with interpolation
same issue
colliders do not move until the physics simulation step
period
unless you call Physics.SyncTransforms
okay thank you so much ๐
@cobalt wave
Quaternion targetRotation = Quaternion.LookRotation (path.lookPoints [pathIndex] - transform.position);
transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation, Time.deltaTime * turnSpeed);
transform.Translate (Vector3.forward * Time.deltaTime * speed * speedPercent, Space.Self);
well
the only possible explanation I have is that the path is not on the ground
have you checked the path points individual position?
they're placed on this grid maybe lowering the grid?
yea that should fix it as the grid appears the be obviously "floating"
and if the points are centered to the grid, they will be floating too
why are the waypoints on a grid though?
it works well mostly
like it does find the paths and avoids stuff
I am a good modeller I swear i just cant be bothered modelling anything "good" for this
I'd suggest having some checks for the ground to avoid these sort of issues
instead of having the points be centered to the grid, raycast both up and down (to find the ground) and move them to the hit point
yeah that might be a smart idea
i've rushed it since its just a school project due in a few weeks lol
oh, well then keep that in mind and if you have extra time, add it in :)
i'm sure it'll yield a few extra points
sent you the task outline btw if u wanna take a look
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private float minSpawnInterval;
[SerializeField] private float maxSpawnInterval;
[SerializeField] private float startDelay = 2f;
[SerializeField] private float minX = -10f;
[SerializeField] private float maxX = 10f;
[SerializeField] private float minY = -10f;
[SerializeField] private float maxY = 10f;
private Camera mainCamera;
private float cameraWidth;
private float cameraHeight;
TimerManager Timer;
void Start()
{
mainCamera = Camera.main;
cameraHeight = 2f * mainCamera.orthographicSize;
cameraWidth = cameraHeight * mainCamera.aspect;
StartCoroutine(DelayedSpawnEnemy());
}
void Update(){
if (Timer.currentTime < 10){
minSpawnInterval = 0.5f;
maxSpawnInterval = 0.5f;
}
}
IEnumerator DelayedSpawnEnemy()
{
yield return new WaitForSeconds(startDelay);
StartCoroutine(SpawnEnemy());
}
IEnumerator SpawnEnemy()
{
while (true)
{
Vector2 spawnPosition = new Vector2(
Random.Range(minX, maxX),
Random.Range(minY, maxY)
);
Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
yield return new WaitForSeconds(Random.Range(minSpawnInterval, maxSpawnInterval));
}
}
``` hello guys, i want to make in every 10 second decreasing the minSpawnInterval and maxSpawnInterval by 1 how to make it?
another coroutine
:)
Anyone knows the code that a 2D gameobject follows your MousePosition?
@gray mural if you want any further information contact me on dm please
Use the input.mouseposition
Look it up on google
i dont find anything helpful
Dming you solution, one min
i have an idea for a cool effect that I'm not sure where to start with.
i want enemies to "shatter" when destroyed -- actually turning into a 2D image that shatters into fragments
i feel like i need to do something like...
- render just the enemy to a render texture
- identify the opaque areas and create a mesh that covers it
- cut that mesh up
the enemies are 3D objects
i dont have much experience with character controllers but, i have to ask, why do people use it over a rigidbody? it handles physics for ya (still needs some tinkering) with some work, it can feel really smooth in any context
only benefits of a character controller ive seen is the slope and stair handling thing it has going on, and that it's easier to set up. but i would never use it on a game that has any form of gravity and light physics.
i use character controllers in games with gravity all the time
the character controller isn't simulated by the physics system, so it behaves more predictably
there's a lot of measures that can be taken to prevent rigidbody jankiness
sure, but if the core problem is "I do not want this to be affected by physics", then the character controller does exactly what you want
makes sense i guess
quick question, if I convert a gameobject with a ghost authoring component to a entity, will all its children have their position/rotation networked, or just the parent?
I am allowing users to pick audio file and play it, It is working perfectly fine but some audio is not playing. like audio with missing bitrate.
https://gdl.space/ijinipeqis.cs
How do I fix this?
!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.
anyone here?
kk thx
Diagnose
did you read the first sentence ?
i guess but where else would i ask for help
how do i convert a pixel value to the unity world space value? I currently have the height of my phone in pixels, but need to convert that to the unity coordinate value
it takes in a vector3 though, could i use it for a single value?
your screen coordinate is not a single value, and the z is just used for depth
the height of your phone is not 1 pixel either, u can imagine it as a row of pixels
Well you can just give it a vector that is zero on X and Z but your screen height on the Y or something.
Or define a Z position if you need depth
ah ok thanks
Why is my Unitys Math not mathing
im multiplying negative gravity by deltatime and im getting a positive value#
like what
gravity is negative...
playerVelocity.y += gravity * Time.deltaTime;
is your gravity variable actually negative though
at least, you tend to represent it as a negative number
you should inspect the actual values...
check the inspector
what is the value in the inspector
that's just the default value
the value saved on that instance of the component may be different
e.g. if you originally wrote [SerializeField] float gravity = 9.8f
bruh its 3.51 in the inspector, who did this, imma go ask my other teammembers
thanks i feel so stupid now cuz i overlooked such a simple thing
i was wondering why i was slowly going up instead of falling
check your version control logs if u really need to see who did it
(pls dont say you dont use version control)
at least with git u can see a specific line and see the commit it was changed in
we use plastic
unlucky
i always had a 50-50 shot on being able to switch to a different changeset
"error: file is missing!!!"
yes, plastic, i just deleted it
that might be more of a problem with the integration with unity
idk my entire opinion on plastic is based on the fact many people have had a version bug with it in unity lol
i would also get random popups about the workspace being locked (or some words to that effect)
i just use git without any unity integration now
i dont understand the need for unity integration anyways, github desktop is simple enough to not make major mistakes
Im getting "spammed" with this, in my Debugger and i dont know why...
Cleanup Blit
UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset:OnDisable () (at Library/PackageCache/com.unity.render-pipelines.universal@12.1.11/Runtime/Data/UniversalRenderPipelineAsset.cs:509)
when removing this debug log from code its not saving it aswell cuz its in an dll file
Edit: could remove 2 from LootLocker Addon, but cant edit the file from urp
So, for some reason my unity isn't detecting anything phone-related(Input.touch, IDragHandler), the correct android modules are instaled and the build settings have been switched to android, does anyone know what the problem could be? I wrote a simple touch detector to test and it didn't register.
Hi, I have a TMP_InputField and I am trying to listen to changes on it cs _searchBar.InputField.onValueChanged.AddListener(delegate { listener(); });
and it gets called whenever I type characters except when I delete the last one. Why wouldn't it be sending onValueChanged when it goes to blank? It does have a placeholder text.
I am using the firebase realtimedatabase unity package.
when I call
var task = DatabaseReference.GetValueAsync();
task.Wait();
On a field that doesnt exist, instead of getting back a DataSnapshot, that has a null value and Exists to false, task.Wait() never finishes
anyone has any clue why?
The size you pass to new List<T> is the initial capacity. It'll grow as items get added up. If item count goes past the capacity, capacity is doubled.
If you want to shrink the capacity to the item size, use the TrimExcess() method. Note that this creates a new array internally to fit the new items in, creating some garbage to be collected.
Note that the capacity and item count are different
hey, its quit a while. i have a problem with transformAccesArray. can i post my question here?
this is an inventory system. I made so that after adding another item that goes beyond the list size it won't add another number to the size
and I want to configure the inventory size aka the list size by a script
If the slot count may not change after it's created, then use an array InventorySlot[] instead.
in a click of a button it should go down WITHOUT deleting the content in it
aka the items
and the slot count changes it's ok but the items aka content deletes inside it which I don't want
plus this is the way I tried to change the size of the list
it is wrong cause of the new
the new just gonna make a new list
is there any way to using something else?
you said arrays but I don't want to rewrite the whole system
The list increases its size automatically.
(making the size smaller)'
You usually don't change the size of a list. It's done as you add or remove items, it's not really a size
not increase the size
I'm making an inventory system with the lists
the inventory system needs a limit
so I made it have a limit
Where? I don't see code that limits the size
When you remove an object from the list the object still exists as long you have a reference to it somewhere.
I think it's fine to make a new list, you just need to repopulate it, right?
do you mean get the content and put the content into the new list?
you can also copy a list to array, or to a new list.
This is what I was trying to say but somehow omitted that
or use removeAt, or insert
I never used arrays. Can you change the count in there somehow?
like the size or whatever
arrays dont have a count
the thing that I'm trying to achieve
they have length
No, you need to create anew array
At this point it's just like having a fixed size, that can change once or twice over time. So an array, and to change its size there's Array.Resize()
resize? Explain a little further
The size of the list increases every time someone tries to add a new item to it when it's full. It doubles it actually. E.g. if you have 4/4 items, then add another one, the capacity will increase to 8.
You can use .TrimExcess() to reduce its capacity.
I didn't use trimexcess. I just prevented the player from picking up the item when the list is full or the inventory is full
Arrays have a fixed size. You cannot add or remove elements. You can only set an element at a specific position.
Arrays do not have Add or Remove methods like lists do. If you need to have more or less elements, you need to resize them using Array.Resize
yeah so I can't use arrays then
I'm stuck with lists
I thought changing the size is easy thought?
I just couldn't figure it out :P
They. Have. No. Size
Arrays are perfect for inventories
You need to describe exactly what you're wanting.
Having an inventory with a variable slot count isn't usual
Bear in mind, not the item count inside a particular slot
The slot count itself
ok I'll explain it a little further as much as I can
you see those element thingys. Those are inventory slots. Right now what I'm trying to achieve is remove some of those elements or slots whatever you want to call them.
this is the way im using the transform-job-thingy: ``` public TransformAccessArray transformArray;
void OnDestroy()
{
transformArray.Dispose();
}
IEnumerator Start()
{
transformArray = new TransformAccessArray(spawner.liste.activatedFriendly.Count);
}
void Update()
{
var job = new carJob
{
somevariables
}
JobHandle jobHandle = job.Schedule(transformArray);
jobHandle.Complete();
}````
this is suddenly causing memoryleaks since i was updating to 2022.2 . i read that this warning can be ignored, but its crashing unity if im using another script that is using overlapsspherecommand inside another job
You mean empty them?
I might have tried to explain this stuff way too quickly earlier. Sorry
2022.1 did not throw any errors
just like I removed them in the video
but there was a problem
the items in it got removed too
Yeah that's normal. Changing the size in Unity re-creates a brand new list
the issue is obvious
im really not sure if thats a bug. if needed i can post full code, or setup a simple scene to reproduce
I'm creating a new list cause I don't know any other way to remove the elements
which is why I'm asking for help
@vestal summit
.Count - how many items are in List (includes nulls)
.Capacity - how many items should fit into the list before it has to automatically double it size
.TrimExcess () - cuts the Capacity to Count
.Remove (T) - removes T from the list
.RemoveRange (Int32 count, Int32 index); - removes count items from the list starting from the index index
list [i] = null; - changes the list slot at index i to null
You can create your own Resize function that will execute inventorySlots.RemoveAt(n) where n is a specific index
That way you always use the same list
by the way why are arrays better than lists for inventory systems. You can't add a specific item from scriptable objects
they arnt
its another datatype
Most inventories use arrays because the slot count never changes
yeah mine is different
But for you it does, so arrays are out
the slots will change in my game
yeah
Lists have more features but are slightly less performant.
this kinda helped me understand a little more about lists
ok so I'm just trying to remove the items
So re-create a custom Resize(int count) method on your InventorySystem, that calls Add() or RemoveAt() on your list, depending on whether the new count is greater or smaller than your current count
If the new count is smaller, then repeatedly remove the item at the end of the list until both counts are equal
If the new count is larger, repeatedly add a new slot at the end of the list until both counts are equal
What site to use if posting longer code ? i dont want to spam chat
and there is no site pinned
could do a github jist or pastebin if you like
!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.
im assigning the transformaccses array within the ienumerator-start-method (async) if the condition is meat, but no other method is calling the array beforehand. anyway this is the warning im getting. ```Internal: JobTempAlloc has allocations that are more than the maximum lifespan of 4 frames old - this is not allowed and likely a leak
yeah works thanks @simple egret
the warnign can be avoided as long as im not using any other physics based job that is interacting with the transforms controlled by the Ijobparallelfortransform
So im having an issue, both my isCrouching and isSprinting get sucessfully changed by the button, but for isSprinting it doesnt apply the new tempspeed, it runs into the if case but doesnt like put sprintSpeed onto speed...
https://gdl.space/efepiqoqux.cs
it stays on 5f, but if Crouching is pressed it successfully removes 2.5f, idk what is happening
am i just very blind and missing something obvious ?
its obious
if (isSprinting) { tempspeed = speed + sprintSpeed; }else { tempspeed = speed;}
Debug.Log(isSprinting);
if (isCrouching) { tempspeed = speed + crouchSpeed; }else { tempspeed = speed;}
use a switch statement
Or an else if
yeah i might borked it with that unneeded else i just realised
while looking over it again, let me test
yeah
my brain was not braining
1am brain is real
thank you two

the phenomenon of instantly figuring out what you did wrong as soon as you try to explain it is well known
i have so much energy in me, i couldnt sleep
where can i find related issues to my problem? i cant find anything on the net and i really dont know if its a bug and the method was introduced a month ago. -> 2022.2 is not lts, but its also not an experimental alpha (2023)
this is the crash report snippet ```0x00007ffbca67ecdc (mono-2.0-bdwgc) mono_runtime_invoke (at C:/build/output/Unity-Technologies/mono/mono/metadata/object.c:3113)
0x00007ff7605858d4 (Unity) scripting_method_invoke
0x00007ff760566344 (Unity) ScriptingInvocation::Invoke
0x00007ff76054dc84 (Unity) MonoBehaviour::CallMethodIfAvailable
0x00007ff76054ddaa (Unity) MonoBehaviour::CallUpdateMethod
0x00007ff75ffeae4b (Unity) BaseBehaviourManager::CommonUpdate<BehaviourManager>
0x00007ff75fff265a (Unity) BehaviourManager::Update
0x00007ff76021b82d (Unity) InitPlayerLoopCallbacks'::2'::UpdateScriptRunBehaviourUpdateRegistrator::Forward
0x00007ff760201e3a (Unity) ExecutePlayerLoop
0x00007ff760201fc6 (Unity) ExecutePlayerLoop
0x00007ff760208815 (Unity) PlayerLoop
0x00007ff7611b2ccf (Unity) PlayerLoopController::InternalUpdateScene
0x00007ff7611bfa1d (Unity) PlayerLoopController::UpdateSceneIfNeededFromMainLoop
0x00007ff7611bdd21 (Unity) Application::TickTimer
0x00007ff76164b02a (Unity) MainMessageLoop
0x00007ff76164fdd0 (Unity) WinMain
0x00007ff762a3395e (Unity) __scrt_common_main_seh
0x00007ffc58fa26ad (KERNEL32) BaseThreadInitThunk
0x00007ffc5a08a9f8 (ntdll) RtlUserThreadStart
maybe i shouldnt use transformaccsessarray while using spherecast
apart from this: the provided snipped wont work for me unless i check if the hitcollider.Length is not 0 as well s stopping the iteration if instanceId =0 https://docs.unity3d.com/2022.2/Documentation/ScriptReference/OverlapSphereCommand.html
figured it out. I used the removerange. That works fine
In a Unity 2d project, I have 8 items in a grid layout group. Can an item besides the last one ever be the "top most" (closest to the camera) one? If so, how?
Basically I have a hand of cards that are curved and overlap, that scale up on hover and I want them to appear in front of the cards beside them.
if they are UI objects then they are drawn in the order they appear in the hierarchy so lowest one in the hierarchy is drawn last or on top. also #๐ฒโui-ux
can anyone tell me why vscode is telling me that this class doesnt exist when it is in the project
open the PlayerData file and make sure the class is actually called PlayerData
it is
is it in a namespace you have not imported in this other file?
whats the error you're seeing?
have you actually saved for unity to attempt to compile to show errors?
share both classes with a bin site
k
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ugh of course it's pastebin with no syntax highlighting.
try regenerating project files
or restart vs code
or just use a better IDE that doesn't break for no reason
it's in the external tools settings
IEquippable? equippableItem = other.gameObject.GetComponent<IEquippable>();
if (equippableItem is not null)
{
PickUpItem(equippableItem);
}
else
print("equippable item is null");
```Are nullable annotations being used in Unity? I saw scripts for null check but variable types are not null-capable (without question mark or not Nullable<T> class). Am I asking clearly? 
no, you do not need to mark reference types with ? for them to be nullable in unity. however you should also not be using the is operator to check for null on UnityEngine.Object types (i know the interface doesn't derive from UnityEngine.Object but the component it is implemented on does)
Yeah, I'm aware Unity is overloading == operator and null check is a bit different, but as you noticed it's an interface so I put is not null.
Earlier I was doing desktop applications with Windows Forms and putting ? was a daily routine, here in Unity I don't see it anywhere. You said I do not need to mark them as nullable, but why? Are all objects deriving from UnityEngine.Object nullable by default? (Also thanks for answering my question, after 3rd try only you bothered to answer
)
all reference types are nullable by default. that's how the language has worked since the beginning
The actual object is not an interface, it's a real thing that is a component
okay, I guess I'm slowly starting to understand
it's only c# 10 that has nullable reference types enabled by default, and it wasn't even introduced until c# 8
As I said I was doing Windows Forms earlier with .NET 7 so I guess it was either C# 10 or C# 11
and as I said, I was using nullable annotations almost everywhere
Anyway, thank you both for answering my question!
To be clearer about nullable reference types, the question mark only actually makes something Nullable<T> when it's a value type. For reference types it just informs the compiler to give you static analysis, hints basically, and provides no actual nullability (as reference types can already be null), it only helps protect you against null reference exceptions if you've got the static analysis available and follow its instructions; which isn't aware of how Unity's working with it's fake null object
Alright, got it. Yeah, I forgot Nullable<T> is rather for value types not reference types, thanks again! ๐
feel free to not answer this, but i'm genuinely curious why you chose to use winforms in .net 7 when there are several (in my opinion) better options available now that aren't only restricted to windows
But that was the goal, at my work we work on various Windows Servers ranging from 2000 to 2019 and I needed to build a desktop app that will run on Windows Server 2012 or Server 2016
Windows Forms seemed easy and I didn't need any compatibility for other operating systems
I know it's old and there are better options but as I said, I found it easy and it's not a big program anyway, a couple of forms, some scripts under the hood (about 1,000 - 3,000 lines of code) and that's it
Unity is stuck on C# 8 and partially supporting C# 9, right? 
2021+ supports most of c# 9, yeah
https://docs.unity3d.com/Manual/CSharpCompiler.html
Hi, im following an open world game tutorial on yt and i got this error when trying to deserialize https://pastebin.com/8kCGRKpc, this is the code for the file https://pastebin.com/yMm8pFGC
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
SerializationException: Attempting to deserialize an empty stream. 
it tells u the error, the stream is empty
just FYI you should stay away from BinaryFormatter, it's a security risk
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
its only for save files of a singleplayer game
okay, and if your players decide they want to share save files (which is fairly common) then because you chose to use BinaryFormatter then they potentially open themselves up to malware
but it shouldnt be empty
and idk how to fix this
nevermind, im gonna be encrypting it in json and give up on the binary system so
can I instantiate a mesh multiple times that I generated in runtime?
Generated mesh is fine, but when I instantiate it all their meshes seems to be empty, well not empty but it has no tris and faces
You can instantiate anything you want as many times as you want
I did instantiatedMesh.mesh = generatedMesh.mesh and that seemed to fix it, but not sure why instantiating the generated mesh isnt working
Hey guys, I've been wracking my head over this for the past 4 hours and its going nowhere, i've built a generator that creates "province" gameobjects based on a colormask by doing Texture2D.GetPixel and then using it as an index, issue is i'm trying to get the provinces to actually highlight once clicked based on their shape in the colormask and i havent been able to find a good way to do that, does anyone have any ideas/advice?
What on earth is Mesh.mesh?
Are you talking about mesh renderers?
Don't confuse meshes with MeshRenderers
Its was simplified writing
Code -
_fogOfWarTile is whats generated in code, and fow is the Instantiated one
Sounds like you're instantiating GameObjects, not meshes
Yes i am, I generate a new Mesh, and add components to it, and have it in a gameobject variable, then Instantiate it.
I'm not adding components to a mesh, I make a mesh, make a new GameObject, add Mesh Filter and Meshrenderer to it, add the Mesh to the MeshFilter, add add other components i need for it on it, then I'm trying to Instantiate this new GameObject. Everything seems to be there all the componenets and the Mesh Filter and Renderer, it even has the Mesh name in MeshFilter that I generated, but the mesh in Instantiated GOs are empty (no tris, no faces etc). And the fixed that by doing the above code
hey,
is it possible to add items to a list of 10 items in reverse ?
like add item to the list at the 10th spot then 9th , .... 1st ?
Add it normally then do. list.Reverse()
Ok.
Two things:
- are you aware of the difference between .mesh and .sharedMesh on MeshFilter ?
- are you aware of https://docs.unity3d.com/ScriptReference/Mesh.UploadMeshData.html ?
Read them from the source in reverse
Hello all ,been a while since I've been on ... Can someone tell me why I'm getting this error?
Start by reading and sharing the error message
But it just looks like you never declared that variable
just says it doesn't exist in the current context
All of the declarations are inside preprocessor directives which are false
thanks โค๏ธ
Can I use those if statements at the top
nice trick i'll try it , thanks โค๏ธ
So the variable has not been declared
private readonly?
You need an unconditional else preprocessor directive
Isn't that what I have in the image above?
#if DEVELOPMENT_BUILD && UNITY_ANDROID
string adUnitId = "ca-app-pub-/";
#elif DEVELOPMENT_BUILD && UNITY_IPHONE
string adUnitId = "ca-app-pub-/";
#elif UNITY_ANDROID
string adUnitId = AdMobIDs.ANDROID_BANNER_ID;
#elif UNITY_IPHONE
string adUnitId = AdMobIDs.IOS_BANNER_ID;
#endif
All of those are conditional
And none of the conditions are true
You need an #else
this one should be true , I'm building to an android phone
#elif UNITY_ANDROID
string adUnitId = AdMobIDs.ANDROID_BANNER_ID;
You're not building until you're actually building
Just looking at your IDE the target will be UNITY_EDITOR
Yes and Yes, I did the Upload too
Why does unity keep giving me the error "You are trying to save a Prefab that contains the script 'FirstPersonAudio', which does not derive from MonoBehaviour. This is not allowed.
Please change the script to derive from MonoBehaviour or remove it from the GameObject 'First Person Audio'"? The script does derive from MonoBehaviour. I am confused. Code is https://paste.ofcode.org/yvhX22jd68czWvnLXQDXkK
And while I'm asking for help, what does this error mean? 'StatsBar' does not contain a definition for 'bar' and no accessible extension method 'bar' accepting a first argument of type 'StatsBar' could be found (are you missing a using directive or an assembly reference?) Code is https://paste.ofcode.org/KwhfTGy4Qns53i4pRi7rPB
Where's your StatsBar script. Does it have an accessible variable named bar?
I'm assuming the error is from this line
HealthBar.bar.fillAmount = Health / 100;
Where HealthBar type is StatsBar, but StatsBar has no public variable called bar
your Unity Version?
The error is from lines 25, 26, and 27, and I think it does, but I'm not sure. I've never done status bars before, so I'm following a tutorial.
2021.3.25
This isn't a status bar thing. This is a basic c# thing
You're using something that doesn't exist
How can you not be sure? You just blindly typed what the tutorial did?
It's just checking if StatsBar has a bar variable
Do you know what a variable is
In Python, yes. Is it similar to C# or different?
I highly suggest you go through the unity beginner scripting course on Unity Learn first. You need to have a basic understanding of your code at least if you want to be able to act on the help people give
Ok...
And ask in #๐ปโcode-beginner next time
Share your HealthBar Script
Ok and StatsBar?
also if your Visual Studio is not linked with Unity, PLEASE do so
It will tell you what you doing wrong
using UnityEngine.UI;
public class StatsBar : MonoBehaviour
{
public Image Bar;
public Text numberText;
}```
Well thats it, here bar's B is capital and in PlayerStats its small
I did, but it unlinked, and I can't figure out how to link it again. All the settings in both VS and Unity are the same.
Should be - HealthBar.Bar.fillAmount = Health / 100;
not - HealthBar.bar.fillAmount = Health / 100;
Ok. Thanks. I'm bad at capitalization.
!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.
I've done all that already. It's just not linked. I'll try again.
Try restarting your IDE too
You also need to open files strictly through unity
Question, is it worth it to turn a little sequence like this into something that uses unity's timeline?
Hello I would like some help here is a small video of what it is i dont know how to explain it lol
The red text goes away after 3 or more characters ire in the join input field but not when in the create input field??
They use the same code
Just modifyed so it should work
Here it is
a powerful website for storing and sharing text and code snippets. completely free and open source.
where are you calling ShowMessage1 and ShowMessage2?
well simple, you are calling both of them separately, it checks if Create has 3 letters (it doesnt ) so it sets it to true, then Join has three letters so it sets to false, and true and false, and true and false .........
Fix -
public void ShowMessage()
{
if (Create.text.Length >= 3 || Join.text.Length >= 3)
{
Message.SetActive(false);
}
else
{
Message.SetActive(true);
}
}
have just one function
and check both in one
It didnt work neither of them went on or off
only learning this because of unity. dont they have an option for python or something?
show updated script
a powerful website for storing and sharing text and code snippets. completely free and open source.
yes they do!
dont they have an option for python or something?
youre only going to be paying about 100x performance cost for the same ops
probably more
and code that no one can read
Hey,
Is it possible to make an editor script that listens for a specific script added to game objects?
Or how to get a list of all game objects in edit mode?
SceneManager.GetActive().GetRoots()
you can register the script in an editor static
void OnEnable(){
#if UNITY_EDITOR
MyEditorScript.Register(this);
#endif
}
UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
for editor
example?
you just get the component, set whatever values you need
then EditorUtility.SetDirty(component)
This is what I have now.
But it doesn't increase the value in game objects with the script PersistantValue
public class PersistantEditorValueGenerator : Editor
{
public int persistantValuePointer;
private void OnSceneGUI()
{
GameObject[] gameObjects = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
foreach (var lGameObject in gameObjects)
{
PersistantValue persistantValue = lGameObject.GetComponent<PersistantValue>();
if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);
}
}
private void OnAddPersistantValue(PersistantValue persistantValue)
{
EditorUtility.SetDirty(persistantValue);
persistantValue.value = persistantValuePointer + 1;
}
}
PersistantValueSettings.NO_VALUE = -1
first set value, then set dirty
also GetRootGameObjects() returns you roots
only root objects
you are also doing it every frame
what problem are you trying to solve this way?
Also this will give you a Null Ref exception if you have a root object without the PersistantValue component
Debug.Log is not getting called so OnSceneGUI is not being called either.
[CustomEditor(typeof(PersistantEditorValueGenerator))]
public class PersistantEditorValueGenerator : Editor
{
public int persistantValuePointer;
private void OnSceneGUI()
{
GameObject[] gameObjects = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
Debug.Log($"[PersistantEditorValueGenerator.OnSceneGUI] gameObjects.Length = {gameObjects.Length}");
foreach (var lGameObject in gameObjects)
{
PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
foreach (var persistantValue in persistantValues)
{
if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);
}
}
}
private void OnAddPersistantValue(PersistantValue persistantValue)
{
persistantValuePointer++;
persistantValue.value = persistantValuePointer;
EditorUtility.SetDirty(persistantValue);
}
}
I'm trying to automatically create persistant values for game objects that need them.
for gear placed in the world for example.
runtime id?
is it persistant so always the same?
im asking about the concept you are trying to implement
what would you use the id for? save/load?
networking?
Save and load
editor wont work in build
and i assume you will create object at runtime
you are doing it backwards
That shouldn't matter because I wan't the script to assign the values in the editor so that I don't have to constantly update it myself
I have #if UNITY_EDITOR for the whole file.
If you we're to add a gear item in runtime it would update the persistantValuePointer and it's stored in a game file
So what the problem is I wan't to keep track of how many PersistantValue scripts there are in all scenes only in editor mode.
why are you doing it in editor?
ok let me explain
usually you dont need to keep any persistent runtime ids to anything until you actuall save the game
Yes you do because there are different scenes.
because when you are serializing you will be assigning ids to serialized values
at the moment of serialization
the scene index or any id can be part of the serialized id
Is there an already available ID for each gameobject that is persistent across multiple scenes? Transform data can't be used.
not built in
That's why I'm making this, but please explain.
so the task is only to track the count of them?
total amount? not to generate new ids?
Yes
i assumed that was the method you used to generate the ids
I made the utility work in runtime but it has problem. The maximum amount gear is limited.
public class PersistantValueGenerator : MonoBehaviour
{
public int persistantValuePointer;
private void Awake()
{
UpdatePersistantValues();
}
private void UpdatePersistantValues()
{
GameObject[] gameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
Debug.Log($"[PersistantEditorValueGenerator.UpdatePersistantValues] gameObjects.Length = {gameObjects.Length}");
foreach (var lGameObject in gameObjects)
{
PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
foreach (var persistantValue in persistantValues)
{
if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);
}
}
}
private void OnAddPersistantValue(PersistantValue persistantValue)
{
persistantValuePointer++;
persistantValue.value = persistantValuePointer + (
SceneManager.GetActiveScene().buildIndex * PersistantValueSettings.MAX_PERSISTENT_VALUES
);
}
}
MAX_PERSISTENT_VALUES = 1024
that wont work
as soon as you delete any object with persistent value you are creating a collision
if you generate a new value you will use the count, which will now be -1 which will override the last item id
public class PersistantValueGenerator : MonoBehaviour
{
private void Awake()
{
UpdatePersistantValues();
}
private void UpdatePersistantValues()
{
GameObject[] gameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
Debug.Log($"[PersistantEditorValueGenerator.UpdatePersistantValues] gameObjects.Length = {gameObjects.Length}");
int pointer = 0;
foreach (var lGameObject in gameObjects)
{
PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
foreach (var persistantValue in persistantValues)
{
pointer++;
if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(pointer, persistantValue);
}
}
}
private void OnAddPersistantValue(int pointer, PersistantValue persistantValue)
{
persistantValue.value = pointer + (
SceneManager.GetActiveScene().buildIndex * PersistantValueSettings.MAX_PERSISTENT_VALUES
);
}
I think you said make the pointer localized, because the pointer will be the same if you load a new scene?
Let me know if I didn't get it
what happens when you delete an object
your algo gives it id 2
you delete it, add new object
that new object will get id 2
you have 5 ids, you delete object 3
now you have 4 ids
new new object will get id 5
but you already have object with id 5
What do think the solution to this would be?
Maybe to keep a dictionary of pointers per scene and store it persistently?
{
0: 9,
1: 54,
2: 4
}
key is the scene build index and the value is the pointer
yes either that or use GUID
How to use GUID?
Guid.NewGuid();
How does it work?
generates a unique id
Limits?
you mean cons? its not "human friendly"
How many of them can you create?
it is used globally
meaning same class generates an id that is guaranteed to be unique around the globe for the next thousand years
or something like that
So it uses the system time?
can you just google
So this should work?
public class PersistantValue : MonoBehaviour
{
public string value;
private void Awake()
{
value = Guid.NewGuid().ToString();
}
}
yeah the more i think about it the more i realize there is no way to use counting as valid id
you will have issues with dangling references
meaning you delete something, and the id is still referenced, but since you are basing it on count
you will eventually create an object with that id, and the object can be anything else
its basically a minefield
to avoid that youd have to track each reference to that object and modify it
To avoid you never decrease the pointer. Which is not ideal
that would work
Citing genesys.cloud
"
How unique is a GUID? 128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%"
It does seem to create the same id for each PersistentValue script added it's always something different.
if youre gonna use it, serialize it with callbacks
What do you mean exactly?
implement ISerializationCallbackReceiver
on the mono
have Guid as Guid publically, internally store it as string, then convert to Guid on deserialization
its faster to compare Guids directly than do string comparison
The problem is how can I tell which object needs a certain GUID?
if string.NullOrEmpty()
I mean all the objects are not going to have a GUID when the program is started up.
or guid == Guid.Empty
why not?
serialize it
use [ExecuteAlways] attribute
check the guid in
OnValidate
Reset()
OnEnable()
this will ensure that its generated automagically at all points in editor
and at runtime
public class PersistantValue : MonoBehaviour
{
public string value;
[ExecuteAlways]
private void OnValidate()
{
if(string.IsNullOrEmpty(value)) value = Guid.NewGuid().ToString();
}
}
no
[ExecuteAlways] goes onto the class
it tells unity to run the mono methods in editor
you might need to set it dirty
namespace ---
{
[ExecuteAlways]
public class PersistantValue : MonoBehaviour
{
public string value;
private void OnValidate()
{
if(string.IsNullOrEmpty(value)) value = Guid.NewGuid().ToString();
}
}
}
How would this work for game objects added at runtime?
actually this
public class PersistantValue : MonoBehaviour, ISerializationCallbackReceiver
{
public Guid guid { get; private set; }
[SerializeField] string _guidSerialized;
public void OnAfterDeserialize()
{
if(string.IsNullOrEmpty(_guidSerialized))
{
guid = Guid.NewGuid();
_guidSerialized = guid.ToString();
}
else
{
guid = Guid.Parse(_guidSerialized);
}
}
public void OnBeforeSerialize()
{
if (guid == Guid.Empty)
guid = Guid.NewGuid();
_guidSerialized = guid.ToString();
}
}
should be enough
it wont thats why i said OnValidate + Reset + OnEnable
but that serialization hack should work also
probably
maybe with Awake() injection as well
Hi, Anyone knows how to like animate camera if you enter a collider?
Thanks
@sharp oasis Don't cross-post
Will PersistentValue.guid be different for all PersistentValue instances?
alr
yes
But can you help me 
just double checking this isnt needed for multiplayer
It might be in the future
runtime GUID won't be deterministic, unless you sync it
I can make the server decide
cool, that's fine
at that point though you might as well have used the inbuilt way the networking solution does it instead of making your own persistent values
If I'm going to do multiplayer it's going to be Player hosted server
problem with serialized guid is also that if you copy paste an object it wont have unique guid, youd have to handle it yourself
The serialization doesn't work for new objects at runtime.
GameObject can = new GameObject("Can");
can.AddComponent<PersistantValue>();
PersistantValue.guid will always be different
yeah then awake
what
it will be different because its a new object you are creating
I guess I can fetch them from the gamefile and create them that way
And set the guid in manually
oh you mean the save
yes that part you have to do yourself
ISerializationCallbackReceiver is unity serializer
Where does ISerializationCallbackReceiver save the data?
.asset
or .prefab
on build its all converted into asset bundles
so that thing is only for objects created in editor
This is more of a theoretical question rather than a practical one, but what would be the best way to handle VR body force feedback? Its easy to just put force on the player's body instead of hands when he grabs a static object, but it becomes significantly trickier in the following two cases:
First, what if the grabbed object moves? its easy enough to detect if it's "static" by lack of a rigidbody, but there's no real way to know when to apply force and in what direction in such a case
Second, which is not as important, regarding non-static objects of significant weight, or perhaps when the player doesn't grab and just pushes using their fists. Using physics 24/7 is a bad idea because it will give the player motion sickness from getting their body moved around when swinging objects, especially in the air. First problem could probably be solved the same way this one is. This isn't as important (if it is at all), so I'm mainly focusing on the first issue
There are physics based games where the player can climb by hands etc and push away with them. I think they use joints to accomplish this. Think Valem has some tutorial on this as well.
I am really not a fan of using unity's inbuilt physics components for VR, later down the line it will just become even more of a hassle to deal with if you're doing something more advanced than simple grabbing
I'll look into it tho
I mean it only happends when i build it, when its in unity it works
Can I serialize SortingLayer and then get it's index like it happens in SpriteRenderer ?
In what language should i program in Unity? C# or C++
Scripts are written in C#
I know that, what do you think my response was addressing?
I told that because i checked, and none of the reasons you provided was it, any other directions?
How did you check?
What steps did you take to check
I did nothing in the game related to script execution
That doesn't mean anything
Than what should i do?
Ok, ill try it, thank you
Hey, so in my code, I instantiate gameobjects inside a GridLayoutGroup at runtime. Only thing is they appear invisible at first, same thing in scene view inside and outside playmode. An easy work around is to go in the scene and enable, disable or change any one of the objects in the grid layout group and they all suddenly appear as if something was updated or refreshed. It doesn't work if I just SetActive to false then true in the code instead. Thoughts on how I could fix or hotfix this? Thanks!
SOLVED
LayoutRebuilder.ForceRebuildLayoutImmediate(grid.GetComponent<RectTransform>());
I'm pretty stumped on this one. Trying to use a dictionary of <string[], int>, but whenever I try to look up in the dictionary using a string[], I get the following error:
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <a40b0ad4a868437393ad434631fb6ff1>:0)```
It's as if what I'm looking up wasn't in the dictionary.
Here's my code:
```c#
Dictionary<string[], int> testDictionary = new Dictionary<string[], int>()
{
{new string[] {"A", "B"}, 123},
};
void Awake()
{
Debug.Log(testDictionary[new string[] { "A", "B" }]);
// Should debug 123, right?
}
What am I doing wrong here?
It's right, it's not in the dictionary because it's not checking for the values in the array
you're creating a new string[] so it's not the same one . . .
It checks whether it points to the same location in memory, and since you're creating a new one, it's not
the reference is different . . .
Oooh, you're right, thanks for pointing that out! How would you recommend I go about implementing something like this then?
why are you doing it this way though?
Do I need a Linq expression or just loop through the whole thing?
This is all just test code, as part of a bigger script I'm trying to look up opcodes (ints) for a simulated computer using two strings that identify them.
You can make a custom equality comparer that compares the elements of your array, and pass it to the dictionary when you new it
Sure, that seems like a good idea, thanks. Let me see how well that goes.
I would avoid that if you can. It might make more sense to just use concatenated strings
Is this a performance issue? There's at most about 150 key-value pairs in my dictionary. It'll have to run about 100 times over, do you think that could become an issue
Potentially, it's impossible to say without understanding your use case. It just sounds like there should be better ways of doing this than arrays
If there's only pairs of two strings then you should just make a struct or use value tuples
Thanks, that's a good point, as all of this did seem to be veering into the not best practices zone. I already generated my original dictionary with a python script so I might just write another to make a list of concatenated strings
TextMeshPro somewhy changes the first letter of text. I have this script for floating text:
void FloatText()
{
string test = "";
foreach(var p in FloatingCharacters){
test += (p.character.ToString());
}
Debug.Log(test);
var textInfo = MainText.textInfo;
foreach (TMP_CharacterInfo character in FloatingCharacters)
{
var verts = textInfo.meshInfo[character.materialReferenceIndex].vertices;
for (int j = 0; j < 4; ++j)
{
var orig = verts[character.vertexIndex + j];
verts[character.vertexIndex + j] = orig + new Vector3(0f, Mathf.Sin(Time.time*2f + orig.x*0.01f) * FloatingHeight, 0f);
}
}
for (int i = 0; i < textInfo.meshInfo.Length; i++)
{
var meshInfo = textInfo.meshInfo[i];
meshInfo.mesh.vertices = meshInfo.vertices;
MainText.UpdateGeometry(meshInfo.mesh, i);
}
}
The first letter is not in the list of FloatingCharacters and here's the result:
Hello is there a way to stop a parented object from clipping through other colliders (i'm parenting a box to the player)
The parent should have the Rigidbody
oh damn i'm using a character controller
so maybe disable the character controller and activate the rigid body when the player is pushing the box ?
Anyone extensively used async ? I tested it a bit a few months ago and i'm wondering if there are any limitations to it
I got to use Task.Delay() and it did work
I don't know if CC supports extra colliders but you shouldn't use it with a Rigidbody
You can try swapping between them but its probably going to be janky
yeah worth a try thanks for the insight
webGL afaik doesn't support it (yet)
Oh
What did you try?
async void Start()
{
await Task.Delay(5000);
Debug.Log("Done");
}
Oh sorry I read "did not work"
I'll try more stuff later
I have been using basic delays like that and awaiting other async methods
It could be extremely useful if it doesn't do weird stuff
No major problems so far
Oh nice
dont crosspost bruh
sorry
nvm got it
So I have a gun that shoots every .2sec. The animation is also .2 sec long. therefore, when firing the gun full auto, sometimes the shoot anim wont play because the fire rate and shoot anim are so close together that they conflict sometimes. How can I make it to where the shoot animation plays even if it is already in progress?
I have a wave spawner script like this:
https://gdl.space/sawaqudave.cs
I used to tutorials to build it up but I couldn't find anything related to 3D infinite wave system. So I would like to have wave system, where waves are infinite and the amount of zombies are increasing every wave. Can anyone help me out a lil bit?
How can I make a telescoping tower that opens each section once the last section reached it max position?
Hey, so I wanted to make a variable that only accepts scripts that inherit from a specific abstract parent class called TriggerScript so I can make sure all the scripts have one specific method I need to call. However
public TriggerScript script;
doesn't allow me to enter any script. Not a script that inherits from that nor the TriggerScript itself. Is it possible to make sure that the script I enter is inheriting from TriggerScript or has a method with a specific name?
What do you mean enter..?
like in those [SerializeField]s basically dropping them in there
What are you trying to drop in though.. ?
Look up how to expose abstract classes in unity
I know normally you can't. You need a workaround
But there isn't enough information to know if that's necessary. If TriggerScript is a MonoBehaviour (for example), it should work fine
so this would be the component. and I would like to drag and drop/enter/select only c# scripts that inherit from a specific abstract class so I can make sure they all have the abstract method trigger()
That's not how it works though, you need a specific instance
You can't just choose a script to drag in
you need an Object that has that script on it
That way you create a reference to the specific Object by dragging the object itself (or the specific instance of that script) onto it
Maybe he means a script component and not a script file
AFAIK you do need [SerializeReference] and some custom inspector logic to do this
This mentions SerializeReference
Can you screenshot what you are trying to drag into the slot?
this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerTest : TriggerScript
{
public override void trigger()
{
Debug.Log("Triggered!");
}
}
You are trying to literally drag the C# file onto the slot?
Just want to make sure I understand
yep the parent class inherits from MonoBehavior so I should have all the functionality
So, again, that's just not how it works. You need a GameObject to exist that has the script on it
You could then drag that specific GameObject / Component into the slot
But this likely isn't what you want
So the short answer to your question is.. You can't do that, you would need to find another way. Perhaps ScriptableObjects?
public abstract class TriggerScript : Scriptablebject {
public abstract void Trigger();
}
[CreateAssetMenu(fileName = "NewTriggerTest", menuName = "ScriptableObjects/TriggerTest")]
public sealed class TriggerTest : TriggerScript {
public override void Trigger() {
Debug.Log("Triggered!");
}
}
You would then need to right click in your assets folder and create an instance of the ScriptableObject called TriggerTest. Then you could drag the ScriptableObject instance into the slot instead of the C# script.
Okay let me explain what I want to do with these scripts. maybe then it's better to understand.
I have the gameobject Trigger that I want to use for multiple trigger events. Like change music, play a sound effect, display text etc. And one trigger event should execute a script so a npc walks to a specific position, etc Does this work with ScriptableObjects? I am sorry. I never used them before. should have asked in #๐ปโcode-beginner I guess sry
It could, but you would probably need to learn about many things, and how to structure your code in such a way that would make this possible. What you are trying to do is not necessarily easy. However, as a beginner, if you understand the concept of Singletons, you should be able to make it work with ScriptableObjects.
is there a reason you're not just inheriting from MonoBehaviour and adding the different types of triggers as components directly?
That's probably a better idea haha
Just put your TriggerTest onto the GameObject that has the Trigger on it
Then drag in the TriggerTest (the component, not the script), into the slot
I thought that having one trigger prefab you can change with a dropdown would be easier than having 5 different ones. Thought I'd code smart
๐ซก
it works!
thank you ๐
So I have a gun that shoots every .2sec. The animation is also .2 sec long. therefore, when firing the gun full auto, sometimes the shoot anim wont play because the fire rate and shoot anim are so close together that they conflict sometimes. How can I make it to where the shoot animation plays even if it is already in progress?
it needs to be able to interrupt itself
this is an animator problem
you'd want to add a transition from the state to itself
Hi guys I'm very confused, been trying to get this to work for a few hours yesterday and today in many different ways with the same results.
I'm clearly missing something.
I'm trying to store an array of game objects in an InstantiatedShip class and set them to inactive like this. This is done through a class with a singleton (which is the only thing I can think of being the problem)
InstantiatedShip newShip = new InstantiatedShip(faction, selectableName, type, shipStats.baseHealth, shipStats.baseArmor, shipStats.baseHull, shipStats, isAI, shipReference, cargo);
foreach (Transform g in shipReference.transform.GetChild(1).GetComponentInChildren<Transform>())
{
Debug.Log(g.gameObject);
g.gameObject.SetActive(false);
newShip.turretMounts.Add(g.gameObject);
}
However in another class I am calling this
(something).currShip.turretMounts[0].SetActive(true);
The class is active since I can console.log it, it's pointing to the correct items, the correct game objects, the correct ship, etc. Everything is perfect from what I gather yet it does not actually enable the game objects.
However when the top code runs, then I comment it out, the objects stay inactive (which is probably the issue). Does anyone know why this might be? Maybe there's something about the engine I'm not sure of
i don't understand what this means
However when the top code runs, then I comment it out, the objects stay inactive
do you mean that you comment out jus the foreach?
also, what is the singleton?
i don't see any singletons here
I want to have an area designated by 4 corners (I just need to randomly pick points inside that area latter). What's the best way to store this in code so that I can edit the area in the editor?
I have a monobehavior that has OnValidate() { Debug.Log(GetComponent<Someother>().test) }, that test variable is set to 10, but this outputs 0. Why does this happen? Doesnt OnValidate run after all components have initialized?
OnValidate runs after changing a property in the inspector, iirc
how are you setting this "test variable" to 10?
do you mean it has a default value?
e.g.
int test = 10;
I comment out the actual setting active / deactive of the code. Also yes there's a singleton I just didn't think putting the entire singleton was relevant to the code since ... you've probably seen a singleton pattern
that won't affect the serialized value. the default value is only relevant when you add a new component or Reset a component
no, it is a serialized field, and I set it from the editor
anyway the solution was that the reference I was using was a prefab and not instantiated (though I thought it was instantiated) so i scoured the code and ensured I was doing it to the instantiated object and now it worked
but when the script changes and thus the scene reloads, the outputed value will be 0, even though I set it via the editor to 10
ah, yes, that would do it
so just to reitarate. I have a GO with scipts A and B. A has an OnValidate() with Debug.Log(GetComponent<B>().test), and on the GO in the inspector I've set test to 10
but it outputs 0 when the scene reloads because of a changed script for example
which apparently also calls OnValidate
on A
so my question is, why doesn't A have the proper B instance or whatever else is happening
if I change values in the inspector, it works fine
but whenever I change a script and unity reloads, it outputs 0
i'm not sure if what you're doing is valid
Note: You should not use this callback to do other tasks such as create objects or call other non-thread-safe Unity API
im not instantiating anything, just calling GetComponent
found this thread which seems to talk about the same thing, but i dont really understand what is going on atm https://forum.unity.com/threads/how-does-onvalidate-work.616372/
That's not quite true. If you dissamble some UI components of Unity's, you'll see plenty of component fetches via .OnValidate().
so that does suggest it's valid
in some contexts, at least
I'm guessing you're spotting the component before it gets its serialized values written to it?
Definitely not very clear..
what happens if you set the default value for the field to something else?
like public int test = 3;
still 0
on build. on actual inspector value changes, it works fine and outputs 10
You mean when you start a build?
yes, but not explicitly. by changing a script, and then going back to unity. that triggers a re-build, right? or am i mixing the terminology
Thats a recompile
i might casually call that a "build" in other contexts
but in unity you use that to refer to building the game into an executable
You have to put an f when when assigning a Float
Otherwise the compiler thinks youโre trying to assign a Double
Right?
not quite
you have to add an f to the end of a numeric literal to make it a float
a "literal" is something that's...literally the value
'a', "hello", 123, 4.0, true
4.0f is a float
4.0 is a double
Yeah, but like what helps the compiler understand what is a float and whatโs a double, I assumed the F
if you want to be specific you can do 2d to indicate a double too
which could be relevant!
Oh lol I was just thinking about that, โBut why canโt they just make D mean double?โ
Thanks for all the info
and then there's var someNumber = 1 which will resolve into an int x)
Yeah var is kinda like a dynamic variable
Itโs pretty useful
nah it's just syntactic(?) sugar
yeah, it's sugar
Oh alright
dynamic is, indeed, a thing
I used it once for some code involving calling a generic function with an enum type determined at runtime
scary
Damn, so many keywords lol
yeah don't overcomplicate stuff too much though youll barely use them
in case you want to enjoy all of the keywords
i've never ever seen volatile in a C# script
scary
in C, at least, it tells the compiler to not try to be clever with the variable
no assuming it keeps its value until written to again, for example
Do most programming languages have about the same about of keywords? Or do older ones have less
i dunno
fixed is also scary
hang on, how on earth is fixed less scary than yield or implicit
get outta here
yield can definitely be scary
Thank god documentation exists for all those words
anything coroutine related can be scary
multithreading yikes
coroutines aren't parallel!
When the audioClip ends - I should start the new one. The clip is changed a few times in Update's else block.
private void Update()
{
// that's not full Update code
if (audioSource.isPlaying)
{
if (!changingTime) timeSlider.rawValue = (int)audioSource.time;
ChangeTimeInputText();
}
else
{
print($"started: {audioSource.isPlaying}; \nclip: {audioSource.clip.name}; \ntime: {audioSource.time}");
PlayBackgroundMusic();
ChangeTimeSlider();
Debug.LogWarning($"CHANGED: {audioSource.isPlaying}");
}
}
private void ChangeTimeSlider()
{
timeSlider.minValue = 0f;
timeSlider.maxValue = (int)audioSource.clip.length;
musicParsedLength = ParseMusicTime(audioSource.clip.length);
ChangeTimeInputText();
}
private void ChangeRawValue(float rawValue)
{
if (!Mathf.Approximately(timeSlider.rawValue, timeSlider.maxValue) && !(rawValue < 0 && timeSlider.rawValue <= timeSliderStart))
{
timeSlider.rawValue = rawValue;
audioSource.time = timeSlider.value;
}
}
what's the quesiton?
"How do I make the audioClip to be changed just once?"
Audiosource you mean , I don't see audio clip changing or am i blind
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
we were looking at this a day or two ago
yes, yesterday
it seems like isPlaying is snapping back and forth for some reason
and I haven't fixed it yet
I guess
sucks audiosource doesnt have event
it becomes true immediately after playing
but then appears to go back to false
which is very odd.
what is the end goal, maybe there is alternatives
is this like a music player or something
no, that's just background music with DDOL in the game
also where is this code from
oh, I am sorry, I gave you wrong method
private void PlayBackgroundMusic()
{
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
audioSource.Play();
print($"PLAYED: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");
}
private void ChangeTimeSlider()
{
timeSlider.minValue = 0f;
timeSlider.maxValue = (int)audioSource.clip.length;
musicParsedLength = ParseMusicTime(audioSource.clip.length);
ChangeTimeInputText();
}
the goal is to understand this silly issue and change the music just once
also there are logs after placing few prints
so it's not multiple copies of the same component
these are happening at different times
that's a very interesting time, though...
yeah starting from 0 and then ends at 165
yep.
gets the length after playing
hmmm
!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.
nvm that
maybe that can be because I am changing "rawValue" of timeSlider that is SliderExtension : Slider
idk using Update is weird to me
I would just use a coroutine and while loop
maybe use isPlaying only as extra measure
what do you mean?
yeah, I have tried
no succeeded as you can see
one sec
do you want an example
you can adapt the rest yourself
please ??
[SerializeField] private AudioSource audioSource;
[SerializeField] private List<AudioClip> clips;
[ContextMenu("Play")]
public void Play()
{
StartCoroutine(PlayMusic());
}
IEnumerator PlayMusic()
{
audioSource.clip = clips[Random.Range(0, clips.Count)];
Debug.Log(audioSource.clip.length);
audioSource.Play();
while (audioSource.time < audioSource.clip.length)
{
Debug.Log("Playing" + audioSource.time);
yield return null;
}
Debug.Log("Done");
yield return PlayMusic();
}```
Just tested this and works
wait i think it needs tuning ,
I have a few questions if you don't mind.
- What is
ContextMenuand do you need it here? - The Coroutine returns itself? So starts itself?
- Do you need to use
yield return null;?
- So you can right click on script and run the method from that, you don't need it
- yes when it ends it repeats it
- yes or you get infinite loop
how does it help you to avoid infinite loop?
it pauses the loop until the next frame doesn't block other code from executing
oh, thanks, I see
I gonna try it now
@potent sleet you can also do this way I guess
[ContextMenu("Play")]
public void Play()
{
StartCoroutine(PlayMusic());
IEnumerator PlayMusic()
{
audioSource.clip = clips[UnityEngine.Random.Range(0, clips.Count)];
Debug.Log(audioSource.clip.length);
audioSource.Play();
while (audioSource.time < audioSource.clip.length)
{
Debug.Log("Playing" + audioSource.time);
yield return null;
}
Debug.Log("Done");
yield return PlayMusic();
}
}
you could but now you have no way to stop it
do I need to have a way to stop it?
normally you'd make a
Coroutine playingMusicRoutine = StartCoroutine(PlayMusic());
yeah
not really
hm, yeah, I gonna try to implement it now
I should work I guess ??
it should still work
hey, any way i can animate a mesh vertices in a performant way?
SetVertices per update sounds terrible
Manually change the vertices? tho i don't know much about this
So it could actually be the same thing
what do you mean?
im trying to use a DoTween.To that calls SetVertices in its tween OnUpdate callback
but performance is terrible
Is there a reason why making the animation using vertex shader wouldnt work?
I still have the same issue
private void Update()
{
if (audioSource.isPlaying)
{
if (!changingTime) timeSlider.rawValue = (int)audioSource.time;
ChangeTimeInputText();
}
else
{
print($"started: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");
ChangeBackgroundMusic();
Debug.LogWarning($"CHANGED: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");
}
}
[ContextMenu("Play")]
public void ChangeBackgroundMusic()
{
StartCoroutine(ChangeBackgroundMusicHelper());
IEnumerator ChangeBackgroundMusicHelper()
{
audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
audioSource.time = 0f;
Debug.Log(audioSource.clip.length);
audioSource.Play();
ChangeTimeSlider();
while (audioSource.time < audioSource.clip.length)
{
yield return null;
}
Debug.Log("Done");
yield return ChangeBackgroundMusicHelper();
}
}
Uhmm its actually a terrain editor so i just thought on directly calling dotween when im about to modify it
why is it in update?
i -could- do it on shader but in the end im modifying the vertices so idk
oh. haha.
@gray mural I g2g bbl
just don't put anything it update. call it once. that's it
yeah, sorry
Um, so I dont quite understand what you are using the dotween for? For tweening each vertex separately? If so, that sounds bad
im only tweening 5-10 vertices from the mesh once
is it that bad?
i mean it seems like lol. but they aint that many
Have you tried not tweening at all and just setting the vertices every frame to make sure its problem with setvertices call and not the tweening etc?
yeah its setVertices freezing it
maybe iยดll just drop the idea, just wanted it good looking but not worth the hussle
How many vertices are there in the mesh?
250x250 plane
Thats something but not a lot
yeah
Thank you for your help.
There is still the same issue though.
Could you show your implementation?
i have a conversion uni-dimensional to bidimensional in between that may be adding up unnecesary load.
Gon remove it and see if it speeds up the process
i wanted to treat it as matrix but i could just have used column / row index
You can just have a 1D array and a getter method that takes X and Y
Im afraid that you are doing something crazy every iteration of vertex array so id like to see the implementation
yeah it was silly to do it that way, im going to refactor
if i remove the setVertices form OnUpdate and call it just once at the end its alright, so it may be the ConvertArray conversion
You are also calling the setverticed and setcolors each ieration, exactly as I thought
im not sure how to scheadule it to animate with the DoTween
before using DoTween i would only call it once when i clicked
So youre trying to actually animate it so the terrain changes gradually?
just the couple vertices i modify, (5-10 usually)
But as Osmal said, ConvertArray seems unnesessary anyway, sounds like tons of garbage
but its honestly more worth it to throw in a VFX and just directly modify it
the test/script worked for me ๐คทโโ๏ธ something you're not doing correctly
yeah i just didnt want to spend much time on it, its in-editor tool so not really need to make custom shaders just for me tbh
if i put terraforming in game maybe iยดll dedicate more to it
Thank yall by the way, iยดll start by cleaning up extra code ๐๐ป
Hey, I have chaining coroutines for a turn based game, how do I go about stopping the game (when the player gives up) without it breaking the game ? Do I check every frame of every coroutine if the player has given up?
Chaining coroutines?
{
yield return StartCoroutine(PlayStartTurnText());
yield return StartCoroutine(currentlyPlaying.PlayStatus());
if (gameAlreadyOver)
{
yield break;
}
yield return StartCoroutine(currentlyPlaying.PlayTurn(true));
if (gameAlreadyOver)
{
yield break;
}
currentlyPlaying = GetNextCharacter(currentlyPlaying);
StartCoroutine(PlayTurn());
}```
I have this main coroutine that play a coroutine on another script that's on the character
If you just need to terminate all coroutines, you could use the stop all coroutine function
I wondered about that, cos I have buttons that uses coroutines to animate
I don't know if there's other things that could interfere
Guess I'll experiment with it for now
Can I recalculate static mesh colliders at runtime? I have a procedurally built area and the colliders don't work on convex, but they aren't "static" because I place them at runtime.
One message removed from a suspended account.
do you have a physics raycaster on the camera?
One message removed from a suspended account.
that's why
It looks like that is for rendering multiple meshes at the same time?
Oh, I though you were talking about static batching...
adding a mesh collider to an object with a mesh on it should already Just Work(tm)
I mean not sure why you want things to be static.
I had some modular blocks to build a world with procedurally but the convex colliders weren't any good.
I have decided to use a different method, so it doesn't matter now.
Yeah, but why static ? Is it for the Physics ? Occluding ? Navmesh ?
Then, you do not need to do anything. If I remember correctly, everything that does not have a rigidbody is consider static.
Oh.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemPickup : MonoBehaviour{
public Item item;
public Transform itemSlotContainer;
GameObject trueItemSlotContainer;
Transform slot;
Transform imageContainer;
ItemDisplay itemDisplay;
public GameObject itemImage;
bool slotAvaliable;
void Start(){
trueItemSlotContainer = GameObject.Find("InventoryGrid");
itemSlotContainer = trueItemSlotContainer.GetComponent<Transform>();
}`
for some reason itemSlotContainer isn't being declared on start. does anyone know what im missing
isn't being initialized, you mean?
for transforms, you can just do .transform
but that ~should~ work
perhaps you're getting an error from that line? itemSlotContainer = trueItemSlotContainer.GetComponent<Transform>();
that would happen if trueItemSlotContainer was null
thanks
with the new input system, is there a way to check when a key is released?
#๐ฑ๏ธโinput-system try asking there
oh mb
hello i have a question with unity's trigger system
may anyone help
i am trying to check for collision beetween a car and a check point but i want that to be on the movement script so not on the actual trigger. i dont know how to set that up at all been at this for a while
please ping me if you can help
The script can be on either object, it doesn't matter
ok may you show me how?
If you want to troubleshoot why it's not working, go through this cute little choose your own adventure guide:
https://unity.huh.how/programming/physics-messages
this is on the car script ```void OnTriggerEnter(Collider other)
{
// Check if the collision involves the desired trigger
if (other.CompareTag("aiCar"))
{
points += 10;
print("sup");
}
}```
add a log outside the if statement
to make sure the code is running at all
it defintatly is
and if it's not, follow the link above to find out why
how do you know?
thats in the update function and everything else is running in there
it all works
Your OnTriggerEnter cannot be inside of an update function.
um no
that's definitely wrong then
This is also a #๐ปโcode-beginner question
fuck
don't put functions inside other functions. That's an advanced/intermediate feature.
Don't do it as a beginner.
It will only confuse you
i swear im at this for 30 mins trynna figure this out i just needed some outside thinking
yea its just a brain fart on my end ty
alr swag it works now
Ive run into a really strange issue. after the entire day I narrowed it down to a few lines of code thats causing my bug, but this was through brute force of commenting out code. Im wondering if anyone can help explain this.
The video shows the 2 active ragdolls on the left jittering, they are placed from prefabs. This jittering causes them to move faster than the character on the right (who is moving as i want). The weird part is the character on the right is just a copy of the first prefab, it only got moved to the right. This character has no issues at all. It moves smoothly. This issue started in a different scene, so I made it into a prefab and brought it into this new scene which still has the same issue.
code: https://paste.ofcode.org/38rfU5z4aYGcvw74QKi9nPq
If lines 35 to 41 are commented out, my bug is "fixed" because none of them jitter anymore. But i need the code, it just moves the character in the forward direction of the camera.
Now im wondering why this only happens when I place the character down from the prefab file, and why the copied character has no issues at all. To clarify as well, the copied character is able to move in the direction of the camera easily
`void OnTriggerEnter2D(Collider2D coll){
int i = 0;
if (coll.gameObject.tag == "Player"){
foreach(Transform child in itemSlotContainer){
slotAvaliable = true;//Slot is innocent until proven guilty
slot = itemSlotContainer.GetChild(i);//Cycles through all 15 slots in the grid
imageContainer = null;//Resets called non-cycling variables
itemDisplay = null;
try{
imageContainer = slot.GetChild(0);//Atempts to get child image of item slot frame
}
catch(System.Exception){
slotAvaliable = false;
}
if(slotAvaliable == false){
Instantiate(itemImage,new Vector3(0,0,0),new Quaternion(0,0,0,1), slot);//Instantiates item into inventory
imageContainer = slot.GetChild(0);
itemDisplay = imageContainer.GetComponent<ItemDisplay>();
itemDisplay.item = item;
Destroy(gameObject);
break;
}
else{
i++;
}
}
}
}`
I can only imagine that it would have something to do with the Euler angles not being consistent.
3 backticks to format code, not 1 . . .
for some reason itemDisplay.item isn't being set to item
i debugged this before i added force
Debug.Log(transform.parent.name + direction.normalized + speed);
and all 3 objects were printing the same direction and speed.
Ill check the rotation i guess
If my assumptions are correct, placement would matter.
whats a backtick
Where it may be placed in a certain orientation that allows it's return value of Euler angle to be correct.
they all do have difference rotations being given back from Quaternion.Euler(0f, movementAngle, 0f) so i guess that makes sense. The only thing I dont get though is why it works when i copy the character then move it. Maybe some weird stuff with the configurable joint
the key used to format code. it's the same as the tilde key (on an american keyboard). the same one you already used to format your previous code snippet. just use 3 of them instead of 1 . . .
Smooth damp would iterate towards the specified angle but the possibility that angles return could be 180+ or the opposite would have the target wiggling if attempting to traverse the the opposite direction - a common issue with quaternion to Euler and shortest path.
got it
The usual solution is to not read Euler data from Quaternion and simply have local fields representing angular orientation (in Euler) of the objects.
That would be my only assumption as there isn't much happening with the few lines you've posted - that could go wrong.
NVM i forgot to grab the objects that itemDisplay was modifying in the item display script
I understand how that can be related, but i just dont know why this only fixes for the character that is copied. I think theres just some configurable joint value that probably starts rotated weirdly
also the hip isnt connected to anything, maybe this has some effect
Place the copy where the defects are and with the same settings as the defects. See if it's reproducible.
But definitely reading from Transform.eulerAngles or Quaternion.eulerAngles would throw red flags in my mind.
when i copy the prefab, i mean i literally dont change anything
in that video the very left one, and the one the camera is focused on are the defects. All the copies move fine
the characters u see behind them as well as just for animations, u can ignore those. Theres no script on it, its just a bunch of transforms currently
If you move the defect over there, did it still occur?
Yea if i move them, they still always jitter
i move them all by dragging the CharacterWrapper as well which u can see in the vid
Either way, it's related to those few lines.
I can try just rotating it a different way, maybe the prefab ones have a bugged limit of rotation on some joint
Log direction before normalizing and adding force.
Include the object names (you only need the three) and the direction.
They're all the same, regardless of it they're jittering or not
its printing object name, direction, speed
so it has to be rotation i guess
Log their hip euler angles as well
Wouldn't be surprised if you got some bizarre numbers
im looking through a lot of debug logs and so far they all seem relatively similar. The expanded log at the bottom shows all the details and they never differ by more than like 0.02
the copied character and prefab 2 also are very similar, its only prefab 1 that has the 0.02 difference because its in the middle currently while prefab2 is on the left and copied character is on the right
You've printed the quaternion which would not change
at the bottom u can see the expanded view, i printed 3 things on 1 line. the target angle, euler angles, and quaternion
When the quaternion converts to Euler, you'll not be guaranteed that it's the value you gave it. Example, 270 degrees might not be what it is after writing to and reading back from the quaternion.
ah
So if I were damping towards 270 one frame then -90 the next, I'd get weird wobbling.
Which might affect the speed.
How it's computed, we don't know. But maybe it's got something to do with how near it is to the camera or it's position/orientation relative to the camera etc
The usual solution - tedious.
yea ill probably just rotate it differently then. I tried putting one prefab far away and it is considerably slower nvm its still doing the same
i just find it really odd that its specifically bugged when placing a prefab, but fixed when copying it
That's my assumption what the issue is.
thanks tho ill try to do it without euler angles
Just cache the initial Euler angles and use the cache when needing to read Euler values.
When modifying rotation, you'd just modify those values as well.
Basically your own local Euler angles - not interpreted Quaternion Euler values returned by the euler angles property.
I dont know if I can actually do that for this, because my active ragdoll can fly in any direction when hit
If the rigid body can compute the new direction/angle, so can you - maybe.
Practically though, you'd just avoid ever reading from the eulerAngles property and you'd be all set 
i suck at physics so i probably couldnt compute it. plus the hips can be pushed from other limbs moving and it stands up using joint drives. id rather just learn quaternions
I think it's simply that the quaternion does not retain the angular values and are instead converted to some numerics that can recreate the angles or variants of particular angles. For example -270 may just be referred to as 90 or one of the other periods (360).
even though i shouldnt use euler angles, i still feel like this is a bug with configurable joints specifically. i dont know if i mentioned this before but that code actually worked perfectly fine before today
i just wish i knew what i changed overnight, my pc shut down so something didnt save