#archived-code-general
1 messages · Page 178 of 1
by definition that no longer makes it an auto property and would therefor require being a full property with an explicit backing field
oh youre right actually i forgot
Enabling opaque textures in urp makes everything in the game completely black
why
this is a code channel
[field: SerializeField]
public int x { get; private set; }
well, actually yes, it's the first time I see it
anyway, it won't work if I do like this:
[field: SerializeField]
public int x
{
get;
set => Debug.Log("works");
}
no, as thats no longer an auto property
still need an additional field
I see, but it doesn't make sense in our context, because I wanted to do something when it's set
as it's usually done in e.g. OnValidate
why is that not an auto property?
By definition i think. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
^
then you need a separate explicit backing field and serialize that
or using smth like this with all variables
it should be modified though
you literally wrote an example of it above. It's not hard
this is no different from the property
So which rule is that code violating?
a method is better in this example.
it's a compile error
an autoproperty cannot have validation code
that is different, not the reason given
None, it’s just not an auto property by definition
Not that it’s wrong
yes, I'm being pedantic, but, hey, this is programming, pedantic rules
so I have this in my editor script:
SerializedProperty _meshes;
void OnEnable()
{
_meshes = serializedObject.FindProperty("_meshData");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Debug.Log(_meshes.arraySize);
}
and in my scriptable object i have:
[SerializeField]
Mesh _meshData;
Yet it doesn't seem to work as I get this error Retrieving array size but no array was provided
What am i doing wrong here?
show the full error stack trace?
Retrieving array size but no array was provided
UnityEditor.SerializedProperty:get_arraySize ()
MeshDescriptorEditor:OnInspectorGUI () (at Assets/Editor/MeshDescriptorEditor.cs:17)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
I would guess that _meshData is not actually an array or list
In fact clearly it's not
oh shit
Does a Camera.gameObject that is .SetActive(false) use a non-negligible amount of resources?
no, active false does not mean release of resources
You could profile it to see if you notice any difference. The question itself is kinda odd, but 1 extra camera in your scene probably affects literally nothing performance wise
huh?
2 cameras is quite expensive
Yeah but like a small amount of memory I'd assume
Only one being active at a time I mean
depends on your camera and the platform
That was under the assumption only 1 was on at a time yea since they said setting it inactive
yeah just realized 😅
how do i get my custom struct out of my serialised property ?
i got :
var descriptor = _meshes.GetArrayElementAtIndex(i);
then
var test = descriptor.managedReferenceValue as MyStruct;
but that doesn't work
i cant figure out how to do it for structs
objectValue iirc
How might someone add a description like this to a custom datatype?
Summary with /// it creates template for you usually
tried this and there's still no description when hovering over the datatype
and removing the /// makes the code invalid
oh wait I think I see what the problem might be
nevermind, still nothing
I thought maybe it was changing the second <summary> to </summary>
but that didnt change anything as it stands
so it should go above the thing it's a summary of, like this?
your first picture was wrong because it had no closing tag
ah
yes you can use it above anything pretty much
still not getting a description for some reason
did you save ?
yes
saved, went over to a script that was using it as a test, hovered and screenshot
weird
restart VS? lol
idk
what version you using ?
I reformatted the line to be /// <summary>Test.</summary> to be more space efficient
rather than three lines
should work fine
2023.1.9f1
anything xml in /// should be valid afaik
no such visual studio
oh sorry, thought you meant Unity
unity is irrelevant here lol
yes ur good
I have a physics-related code concern. I put the equivalent of 100 goombas on the screen. They send collision callbacks, but do not send force. If they all overlay, my framerate plummets because I get 100^2 onCollisionStay callbacks. Are there any usual approaches to this?
whats collisionstay do ?
Assume I made a very light but necessary OnCollisionStay(), and I cannot stop the player from putting 100 goombas into a little hole
mostly, if enemy is overlaid with something that should hurt it, kill the entity
sould send messages
because it's a generic script, that would also handle something like a fireball
idk it might be easier to have something else manage the death messages like a main goomba manager that only recives an event oncollision with a specific tag/component ?
onstead of using OnCollision stay you use oncollision enter? or triggers ?
wasnt necessary, I figured out that the problem is that, for some odd reason, if you have a line making the datatype serializable, the summary must be above that, or else Visual Studio throws a fit and refuses to acknowledge its existence
ah you had serializable attribute above it
yeah it probably thought you wanted to try to Serialize the summary or something
I have both, but the function needs to check something to know it has noting to do oncollisionStay
but it needs to do that 10,000 times per frame
can you share code OnCollisionStay method maybe?
that line where we check twice speeds everything up by 2x, because those Actions are null. and they are null every frame.
if I could, I would just block out that whole function if both Actions are null, so it doesn't need to check OnCollisionStay every frame.
oh, that kinda makes sense
order of opperations and all that
Hi guys i have sometime a problem when i check if something is null and when i put an item in the current array there is no erreur like that
if (inventory[i].item != null)
{
slot.GetComponent<InventorySlot>().AssignItem(inventory[i]);
}
yep
but sometime its working so i don't understand ahah
slot could also be null or you don't have InventorySlot on it
no its every time null
use debugger 🙂
i've change to
if (inventory[i] != null)
and im gonna see if its working every time
i check if there is an item or not in the list but when i start the game to test the chest is empty so it null every time
have you actually initialized the array or list
ofc if its working ^^
guys, how can i make a dash movement on mobile? on desktop i'm taking the mouse direction to direct the dash, but how can i do that on mobile?
Instead of the mouse position, take the touch position . . .
Is it similar to your previous code for the mouse? I guess we'd have to see exactly how you dash . . .
Hey if possible I could use some help with the input system rn
it's bugging out on me and I dunno how to fix it
buggin out isn't very helpful or descriptive, also #🖱️┃input-system would be probably a better channel
No. That doesn't explain what you try to achieve. It explain what I already know.
thanks
i guess I’m wondering how Mario maker can let you have 200 goombas on one square, and the game doesn’t chug
dozens of smart engineers who know their own engine
maybe I need to split enemy collision callbacks between enemies and non-enemy entities?
then goomba raycasts forward to see if it needs to turn
idk is 200 raycasts per frame viable? or too much for unity?
or maybe a trigger collider? but idk if a trigger collider with 200 things in it will also give me 200^2 callbacks if everything is in a blob
And some dozen lives by their curse to support their old legacy codes....
@hard viper atleast for goombas, you wouldn't need to actually know it hit a wall. just check if it moved more in that direction compared to last time it tried to move, if it didn't, turn it around
So I'm working through some of Valem's tutorials regarding hand presence, and we're putting these scripts on "Right Hand Model" etc. But, given that these scripts aren't referencing the parent game component directly, and simply have public fields to fill with scripts and references, is the placement of a script on a game object somewhat arbitrary in these situations?
I know it's possible to exclude plugins and foldier using .asmdef to say Exclude this plugin from building on specific platform. However, how can I exclude plugins and folder base on preprocessing directives? E.g.
#if FULL_GAME_ACCESS
// code will be used in full product but not use in any demo product
#endif
I don't want to go through all of the plugin scripts and manually add preprocessing directive, because then that would violates the plugin's term of agreement. (Cannot ship modified source code)
Not entirely sure what you mean. Can you provide relevant screenshots for more clarity?
Why would you need to modify the plugins? You only need the preprocessor wherever you're using that plugin in your code. The plugin code itself is either included or not.
I guess my question is a little more meta than concrete; i have it all working.
But my question is more about in situations like this, could the "Animate Hand on Input" script be placed elsewhere yet still function with the correct references?
does any one know how to paginate my array of elements for a custom inspector such that it paginates before it creates a scrollbar ?
It depends. You can have a script that house reference to all of the appropriate game objects you wish to interface in code.
E.g. You can have a script that depends on the object you apply to
// this attribute will tell unity that any gameobject that have this script must have AudioSource, or unity will add them for you when you attach! (Note it does not assign when it is already attached to the gameobject before adding this attribute.)
[RequireComponent(typeof(AudioSource))]
public class MusicBox : MonoBehaviour {
// because of the attribute, I will be responsible for the audio source.
private AudioSource _src;
// for whatever reason this object may be, Maybe I want it to move on sound source, but using this just an example of optional filler requirement.
[SerializeField] private GameObject speakerGO;
// awake is called before start - acquire component within itself.
void Awake() {
// I expect this gameobject to have AudioSource, or we'll have problems!
_src = GetComponent<AudioSource>();
}
// start called after awake - acquire reference(s) outside this object scope.
void Start() {
// This guy could be null, but would prefer to assign something!
if( !speakerGO && transform.childCount > 0 ) {
speakerGO = transform.GetChild(0).gameObject;
}
}
}
If I do add preprocessor - how could unity retains the reference information? E.g. if the plugin offer new variable types, but need to remove it upon compilation, I don't want to lose the reference when I need to compile for full game access?
Assuming you don't exclude it from compilation in the editor, it shouldn't lose any references. When the build is compiled, the correct defines for the specific platform are set.
Forgot to mention - I'm adding the preprocessor compilation during preprocess build process - By calling this method - https://docs.unity3d.com/ScriptReference/PlayerSettings.SetScriptingDefineSymbols.html inside IPreprocessBuildWithReport https://docs.unity3d.com/ScriptReference/Build.IPreprocessBuildWithReport.html
Builds don't affect the editor environment.
Yeah, I figure if there's a script that references the attached Gameobject direclty it makes a lot of sense, i guess it's a choice of organizational structure otherwise
Must be a good reason to remove public access from designer that'll use your script...
You can sort of use the same principles as with code, namely - the single responsibility principle. It makes sense to put scripts on objects that they "belong" to semantically.
goombas turn around if they touch each other
this just helps spread enemies out to avoid single death blobs with like 50 enemies
(repost since i couldnt get this answered last time around)
Currently I have a whole Rigidbody based first person movement system, and the only problem with it is that it struggles to go up any drastic change in height such as a stair. To counter this, I want to make the player sort of always keep a .5 unit offset from the closest ground to their feet (so floating, pretty much) with the use of a Raycast detecting the ground below them. The way to do this would be to continuously change the Y of the player from the Y of the point of raycast collision plus that .5 unit offset mentioned previously by changing the player's transform. So I did this, it works fine. But is there any way I can fix the jittering?
let me know if my explanation of the whole thing is confusing
Modifying the transform directly will always be problematic when mixed with Rigidbody motion
A better approach would be to add forces as appropriate when on a slope to counteract the influence of the slope
Also if possible use a flat ramp collider rather than jagged stairs
thing is, this has been a good solution for stairs too. but yeah, i guess the ramp solution works too. just been trying to find a way around it if possible. i might have to cut my losses on this
i do a little bit of both. my rigidbody applies forces primarily to go along slope. but I also move transform directly very tiny distances if my collider gets disconnected from floor, which happens if “running off” a slope
but i don’t have stairs. only slope
moving my transform can work smoothly because it is only ever a very small correction, done infrequently
A majority of games don’t use real stairs like that for movement
its all collider ramps
Stairs are actually a really complex physical interaction
Not modeled well with capsule shaped people
stairs are notorious for being hard as shit
Actual stairs are for visuals and if your fancy feet IK
further proves that stairs are just racist against capsule kind
I'm gonna keep messing around with that whole fixed distance from floor thing, see if i can change some things to stop the jitter and other problems im having with it right now
if not then
we'll have to fuck the stairs
not in that way but
im sure you get it
thank you all
Does anybody know how to fix character controller sticking to cielings whn you jump?
maybe its spiderman
Haven't encountered that one 🤔
Actually I guess you're probably simulating velocity yourself? I would just zero out the y velocity if you detect a collision with the ceiling
By chance is ur floor and ceiling the same prefab and the tag on both are set to ground?
yea but my char controller doesnt use tags to detect anything
nahh its this prob what Praetor said
I will try that
You can use the collision normal to see if it was the ceiling. The normal will be facing downwards
the next spiderman unity on mobile
Trying to do marching squares and I just can't seem to get my vertices and indices working. There is almost certainly a mistake in this method, but I can't work out what it would be. ```cs
public static SimpleMesh<Vertex,uint> GetMeshForSquareIndices(NativeArray<byte> SquareIndices, NativeArray<int3> Positions, float HalfWidth)
{
SimpleMesh<Vertex, uint> Mesh = new SimpleMesh<Vertex, uint>(Allocator.Temp, 8 * (uint)SquareIndices.Length, Allocator.Temp, 12 * (uint)SquareIndices.Length);
int VertIndex = 0;
uint IndexIndex = 0; // The worst name of any variable ever!
for (int i = 0; i < SquareIndices.Length; i++)
{
byte SquareIndex = SquareIndices[i];
int2[] Vertices = VertexTable[SquareIndex];
uint3[] Indices = IndexTable[SquareIndex];
for (int vi = 0; vi < Vertices.Length; vi++) // loops over vertices for the specific square index and adds them to the mesh
{
Vertex CurrentVertex = new();
CurrentVertex.Pos = new float3(Vertices[vi], 0) * HalfWidth + Positions[i];
Mesh.Vertices[VertIndex] = CurrentVertex;
}
for (int ii = 0; ii < Indices.Length; ii++) // loop over indices for the specific square index and add them to the mesh, with correct vert offsets
{
Mesh.Indices[ii + (int)IndexIndex] = Indices[ii].x + IndexIndex;
Mesh.Indices[ii + (int)IndexIndex + 1] = Indices[ii].y + IndexIndex;
Mesh.Indices[ii + (int)IndexIndex + 2] = Indices[ii].z + IndexIndex;
}
VertIndex += Vertices.Length;
IndexIndex += (uint)Indices.Length*3;
}
return SimpleMesh<Vertex, uint>.FromRange(Mesh, 0, (uint)VertIndex, Allocator.Persistent, 0, IndexIndex, Allocator.Persistent);
}
You would probably want to put a breakpoint and examine step by step. I usually use async methods with gizmos to animate slowly and debug points visually as well.
Thanks I forgot breakpoints exist lol!
Just tried to compile my first unity app and i'm hitting a breakpoint here.
How would I debug it for iOS?
I mean like where its actually causing it. No such file without knowing a file is hard
2023-08-24 05:15:04.648672+0200 RadarGSI[50161:3578780] fopen failed for data file: errno = 2 (No such file or directory)
2023-08-24 05:15:04.648701+0200 RadarGSI[50161:3578780] Errors found! Invalidating cache...
2023-08-24 05:15:04.962671+0200 RadarGSI[50161:3578780] fopen failed for data file: errno = 2 (No such file or directory)
2023-08-24 05:15:04.962720+0200 RadarGSI[50161:3578780] Errors found! Invalidating cache...
The code runs fine on mac and pc
Figured it was some xcode setting, but now I get this error
Assertion failed: 0 && "RuntimeType::get_DeclaringMethod", file ./Il2CppOutputProject/IL2CPP/libil2cpp/icalls/mscorlib/System/RuntimeType.cpp, line 751
void il2cpp_assert(const char* assertion, const char* file, unsigned int line)
{
printf("Assertion failed: %s, file %s, line %u\n", assertion, file, line);
abort();
}
hey guys, I was wondering if any of you know how to change how the camera in unity's scene view rotates? When I rotate I want it to go left and right from my perspective, but instead it spins my camera the other way. Pretty frustrating.
camera scene view is not a coding question
oh my bad
thank you
If I want to do some drag-to-select stuff in my 2d game, should I draw the box and capture input in a UI layer object? Or is there a better way to do this? In the video above, "UiHud" has a GO called "InputCaptureImage" which is a 0% alpha image over the entire screen so I can capture pointer down/up/drag.
i was just working on my own selection tool, i ende dup making the box in the game layer rather than UI, and added a collider2D to the image that captures selectable colliders when ti drags over them
oh, that's a nice idea.. or I could even do both.. instead of the box, the tiles (in my example) or units, or whatever existed in worldspace .. could receive the "you've been selected" event
the box in world space could even be visible, so i wouldn't need to do anything in the UI layer at all
im probably a worse programmer than you lool, i just do stuff that requires the least mixing of code lol
it's a good idea, though
i also used a line renderer for the box outline, make sit look nice
as it is, I'd need to translate a lot of UI layer coordinates to world space coordinates
yeah thats why im trying to do as much of the game a si can without a canvas
anythign that interracts with the world anyway
my tentative plan was just to make a 9sliced image for this selection box, but i'm finding i'm already doing a lot of translation from UI space (scaled by canvas scale) to/from click space and to/from grid space
hm, the only problem i see is the selection volume might appear weird if you're zooming in/out..
private void SetLineRenderToBox(Vector2 startPos, Vector2 endPos)
{
//Sets position of each linerender line's vertex point
lR.SetPosition(0, startPos);
lR.SetPosition(1, new Vector3(endPos.x, startPos.y));
lR.SetPosition(2, new Vector3(endPos.x, endPos.y));
lR.SetPosition(3, new Vector3(startPos.x, endPos.y));
lR.SetPosition(4, startPos);
//Adjusts line's start and end width to stay the same width durring camera zooming
lR.SetWidth(startLineWidth * (cameraMain.orthographicSize), startLineWidth * (cameraMain.orthographicSize));
//sets sprite renderer gameobject(fillSprite) to center of select box, and scales it to touch the lines of the line renderer (rectangle only)
fillSprite.position = (startPos + endPos) / 2;
fillSprite.localScale = startPos - endPos;
}
```fillSprite is just a gameobject with a sprite renderer and my collider
oh manually drawing the box
//Adjusts line's start and end width to stay the same width durring camera zooming
lR.SetWidth(startLineWidth * (cameraMain.orthographicSize), startLineWidth * (cameraMain.orthographicSize));
hm... I'll have a think on this. I think there's pros/cons but it never occurred to me to do it directly in worldspace
yeah my box is jsut a sprite that fills the positon between where ym mouse starts dragging, and where it currently is/ends being
how are you capturing the initial click and startPos?
uh, lemme check lol
i got soem messy logic in here for now while i test shit, but this
//Sets initial Position of Drag Box if drag SHIFT operator key is pressed and mouse has been clicked down
if (Input.GetKey("left alt") && Input.GetMouseButtonDown(0))//SHIFT | LMB
{
if (debugMode) { Debug.Log("Drag Down"); }
selectStartPos = screenToWorld.MouseWorldPosition;
selectEndPos = screenToWorld.MouseWorldPosition;
selectionBox.SetActive(true);
if (debugMode)
{
foreach (Ship i in selectedShips)
{
i.VarSelectable.IsSelected = false;
}
selectedShips.Clear();
}
}
//Sets Updated End Position of drag Box as long as LMB is held down
while ((selectionBox.activeInHierarchy) && Input.GetMouseButton(0))//LMB
{
if (debugMode) { Debug.Log("Drag Hold"); }
selectEndPos = screenToWorld.MouseWorldPosition;
clickHeldTimer += Time.deltaTime;
return;
}
//redundancy incase for some reason selection box is not active in hiarchy but click heldtimer is
//Comes before ' "X" comment ' if statement below for Execution bug
if (!selectionBox.activeInHierarchy && Input.GetMouseButtonUp(0))//LMB
{
clickHeldTimer = 0;
selectionBox.SetActive(false);
if (selectedShips.Count > 0)
{
foreach (Ship i in selectedShips)
{
i.VarSelectable.IsSelected = false;
Debug.Log("LMB-UP Removing");
}
selectedShips.Clear();
}
}
// "X"
//Resets Drag Box if LMB mouse key unclicked
if (selectionBox.activeInHierarchy && Input.GetMouseButtonUp(0))//LMB
{
if (debugMode) { Debug.Log("Drag Up"); }
clickHeldTimer = 0;
selectionBox.SetActive(false);
}
ah, yeah, I'm probably not going to go that approach (i'm assuming this is in an Update loop somewhere?)
screenToWorld is my mini script for my whole project that translates mouse screen position to world position
all of this is inside a methdo that is insidea an update yeah
this is OK though - I can grok this, it's good stuff, thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenToWorld : MonoBehaviour
{
[SerializeField] private Vector2 mouseWorldPosition;
public Vector2 MouseWorldPosition { get { return mouseWorldPosition; } private set { } }
void FixedUpdate()
{
//sets cursor's canvas position to world vector2
mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
//Sets all active selectables inside of fillSprite collider to selected if not already selected on highlight
private void OnTriggerEnter2D(Collider2D col)
{
Ship i = col.GetComponent<Ship>();
if (i.VarSelectable.IsSelectable)
{
i.VarSelectable.IsSelected = true;
if (!selectedShips.Contains(i))
{
selectedShips.Add(i);
}
}
var test = col.GetComponent<Carrier>();
}
//Sets all active selectables inside of fillSprite collider to selected if not already selected inside highlight
private void OnTriggerStay2D(Collider2D col)
{
Ship i = col.GetComponent<Ship>();
if (!selectedShips.Contains(i))
{
if (i.VarSelectable.IsSelectable)
{
i.VarSelectable.IsSelected = true;
if (!selectedShips.Contains(i))
{
selectedShips.Add(i);
}
}
}
}
//Sets all active selectables exiting fillSprite collider to unselected
private void OnTriggerExit2D(Collider2D col)
{
if (selectionBox.activeInHierarchy && col.isTrigger)
{
Ship i = col.GetComponent<Ship>();
i.VarSelectable.IsSelected = false;
selectedShips.Remove(i);
}
}
and i use the OnTrigger methods for drag box action
again, messy, cna be cleaned, but it works
yup, got it.. and i'm assuming when you release, you call all those objects and IsSelected=false them
Yep, I got the concept, I just hadn't thought of using a collider and a worldspace box for a selection tool
it's good
very helpful if youre just doign rts style stuff
ya that's exactly what this is
same D:
the drag in action
@modern creek last thing, if you use the lien renderer for an outline like i did, make sure the line renderer "SetPosition()" methods are called before your input, otherwise it wont update as you drag, idk why it does it, not bothered enough to care
interesting, cool, thanks
I probably won't use a line renderer (we'll have assets for a dragging box/volume) but it's good to know nonetheless 🙂
i dont like 9-slicing cuz i have camera zoom
so i like to set the width of the lines with line renderer
thats the downside of it being in world space
aye - it's a point in favor of doing it in the UI layer, or in some combination of UI layer + world space
in general I don't render stuff myself.. we have artists for that 😉
im just saying, if you got camera zoom, your box outline will feel weird without scaling
hense i chose linerenderer
how would i get the sprite off a texture2d?
Doesn't sound like a coding question
I'm doing it through code
you tryign to null the variable, or add something into it?
This is a texture 2d https://docs.unity3d.com/400/Documentation/Components/class-Texture2D.html
Do you see any field for Sprite? No.
Yeah I'm aware mate, that's why I asked the question 😄
It doesn't have Sprite
No but like, it does
pic?
A Sprite is an image that can be used as a 2d object, which have coordinates (x, y) and which you can move, destroy or create during the game. A Texture is also an image, but that will be used to change the appearence of an object.
?
youre using an image as a texture, not as a sprite
I don't believe so?
are you trying to like, convert a texture into a sprite?
Do you have a texture or a sprite?
Are you trying to create a sprite?
Both, I'm trying to get a reference of the sprite from it's Texture
you cant do that at runtime
Why
int he editor, you use an image, to create a 2D texture, that 2D texture is its own thing converted from an image.
you can make a painting with paint, but you cant make paint with a painting type of thing
But are sprites not saved as Texture2D's?
There are no sprite properties to be extracted
if i rememebr technically no, you can convert a texture2D to a sprite, but you cant refference the original image and change it to change the texture
I don't understand where they exist then
The slicing operation likely creates a bunch of sprite assets for you - assuming those are what you're trying to access. Create your own sprite from the texture 2d if needed.
Else the assets should be in your project directory
Doing some code to ref. the right sprite asset I want depending on context
Pretty much.
You can get texture from sprite, not the other way.
Multiple sprites can use same texture, thus finding sprite with texture does not make sense for general API.
You can build own Dictionary if that really is usecase
Does anyone know how I can offset a vector3 to be perpendicular to rigidbody rotation
currently my object moves left of the direction it is facing
Show your implementation of move
Oh thanks for responding, I realised I'm actually an idiot and my Vector3 was all in the X direction rather than Z, which is what I needed. However I got the jittery physics movement so I decided to try AddForce instead
How the IPointerHandle works? Like how does it get Invoked?
I thought interfaces just a contract that says "You need this method."
They are indeed. The event systems finds components that implement the interface and invokes it's method.
can anyone reccommend a good tutorial on making sprites on blender
this is a code channel, there is a blender discord
How did they do in TMP_Dropdown so that the the method is called when value is changed in the inspector if they don't have OnValidate method?
So my goal is to do the same as they have done in my code
Probably a callback
an UnityEvent?
Probably a custom editor/inspector with a property.
TMP_Dropdown has an onValueChanged event IIRC, and the custom drawer is probably listening this
Hello everyone. Today I ran into a problem. I have a LeaderboardManager with Leaderboard (Script) attached to it, and it is on my first scene. It worked normally until I changed to the second scene and went back to the first scene, then I got this error:
Then I checked the GameObject, and I still saw my LeaderboardVisual attached to it:
In detail, I have a code block in my PlayfabManager, which is DonDestroyOnLoad:
{
Debug.Log(OnGetLeaderboardSuccess.GetInvocationList().Length);
var request = new GetLeaderboardRequest
{
StatisticName = "Star",
StartPosition = 0,
MaxResultsCount = 30,
};
PlayFabClientAPI.GetLeaderboard(request, result => OnGetLeaderboardSuccess?.Invoke(this, new OnGetLeaderboardSuccessEventArgs
{
result = result
}), error => OnPlayfabErrorEvent?.Invoke(this, new OnPlayfabErrorEventArgs
{
error = error
}));
}```
In Leaderboard - which attach to a game object that not have DontDestroyOnLoad, I have this to handle event fromPlayfabManager:
{
Debug.Log("Got the data from playfab:" +e.result.Leaderboard);
playerLeaderboardEntries = e.result.Leaderboard;
Debug.Log($"Entry count: {entries.Count}");
if(entries.Count > 0)
{
for(var i = entries.Count - 1 ; i >= 0 ; i--)
{
PoolUILeaderboardEntry.Instance.ReturnToObjectPool(entries[i]);
}
}
entries.Clear();
for(var i = 0 ; i < playerLeaderboardEntries.Count ; i++)
{
UILeaderboardEntry entry = PoolUILeaderboardEntry.Instance.GetFromObjectPool();
entry.SetLeaderboardEntry(playerLeaderboardEntries[i]);
entries.Add(entry);
entry.transform.SetAsLastSibling();
//Check for leaderboard delay
//if(playerLeaderboardEntries[i].PlayFabId == UserAccountManager.playfabID)
//{
// if(leaderboard[i].StatValue != UserProfile.Instance.highscore) UserAccountManager.Instance.GetLeaderboardDelayed("Highscore");
//}
}
//leaderboardVisual.Show();
Debug.Log("Leaderboard Visual ID: " + leaderboardVisual.GetInstanceID());
Debug.Log("This is the craziest thing i ever seen");
}```
Now when I run my game for the first time, it worked perfectly. But when I switch to second scene and go back to the first scene, it shows the error.
Debug when error occurs, I have 2 Leaderboard Visual ID: One negative and one positive
And if an switch to second scene and go back to the first scene again, i the 3 Leaderboard Visual ID
So I'm thinking that the problem might be in the event part when there are 3 instances listening to that event.
How can I fix that 😦
Could you show us a screenshot of your DontDestroyOnLoad scene hierarchy? I think i might know what is happening
Here is the screenshot of my hierarchy. My Leaderboard script attact to LeaderboardManager, and PlayfabManager script attach to PlayfabManager
Your leaderboardmanager is getting destroyed on scene change, and from what i assume, your playfabmanager needs a refference to it. Either make your leaderboard manager part of DontDestroyOnLoad using a singleton pattern, or program a function to get the refference on scene changes
Yeah im thinking about making LeaderboardManager be DontDestroyOnLoad, but... I really don't want to do that because my second scene doesn't need to use that. And I think PlayfabManager doesn't need to have a Leaderboard reference, because it only Invoke an event when it gets leaderboard data from Playfab. I think the problem is when I come back to the first scene from the second scene and PlayfabManager Invoke the event, I have 2 event subscribers to that. The first one is the first Leaderboard when I start the game, the second one is the Leaderboard when StartScene is loaded again. The proof is at Debug.Log("Leaderboard Visual ID: " + leaderboardVisual.GetInstanceID()); , it shows me 2 results: Leaderboard Visual ID: -1344 and Leaderboard Visual ID: 100122.
According to what I read from Unity document here: https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html
I'm pretty sure there are 2 Leaderboards that exist when the error occurs.
And the other proof is, when I modify Playfab_OnGetLeaderboardSuccess function, with this:
{
leaderboardVisual.Show();
}
else
{
Debug.Log("It should not be shown");
}
If only one Leaderboard exists, it should show the log: "It should not be shown" but I got the LeaderboardVisual show up, and that log too.
Do you unsubscribe your listeners properly before leaving the scene the first time ?
Yeah i'm not unsubscribe it. So now how can I unsub that event when i change to my second scene :((
Is it your leaderboard that is subscribing to your manager ?
yeah. Leaderboard is sub and Playfabmanager is pub
Then, in your leaderboard script, you should add the unsub in OnDisable()
How do you do your subscription in the 1st place ? with a += ?
i have a first person camera system setup with the new input system and its jittery and i cant figure out why controls.player.mouselook is a vector 2 set to mouse delta
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
[Range(0f, 100f)]
[SerializeField] float mouseSensitivity;
public InputMaster controls;
[SerializeField] Transform playerBody;
float xRotation = 0f;
[Header("Clamp")]
[SerializeField] float minClamp;
[SerializeField] float maxClamp;
private void Awake()
{
controls = new InputMaster();
Cursor.lockState = CursorLockMode.Locked;
}
void OnEnable()
{
controls.Enable();
}
void OnDisable()
{
controls.Disable();
}
void Update()
{
float mouseX = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().x;
float mouseY = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().y;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, minClamp, maxClamp);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
} ```
Yeah I do that at Start()
Then, do the same in OnDisable, but replace += with -=
is there any way to set a default parameter for T ?
public class OptionSelectionField<T> : MonoBehaviour where T : Component { }
public class OptionSelectButton<T> : MonoBehaviour where T : Component { }
or do I have to create an overload?
Hahaha, it totally worked. Thank everyone a lot <3. Love you alll
Glad it solves it !
I want to make its default value to be a UnityEngine.UI.Button
So a default type ?
yes.
I've just learned Unity & C# for about 3 months, so there are lot of things i didn't know
what is "a s" ?
You'll need to define a proper class that inherit your generic unfortunately
you can do that, which i found on internet:
public class OptionSelectionField<T> : MonoBehaviour where T : Component
{
// Default value of T is set to Transform
private T selectedOption = default(T) ?? (T)(Component)(Transform)null;
}
it won't work
I have to make it work like that: OptionSelectionField field;
without <T>
but ofc it throws an error
so I have to do OptionSelectionField<Button> field
that's annoying.
anyway.
What's your objective with that ?
You just want a default behaviour ?
Or is it to gain something like time typing ?
as you may understand, I have fixed it using this method:
public class OptionSelectionField<T> : MonoBehaviour where T : Component { }
public class OptionSelectionField : OptionSelectionField<Button> { }
just wanna make a default parameter
Yeah, the normal method
it's more comfortable when I don't have to specify a T
There is no such thing, what you did is how it is meant to be done
any way to let unity support opengl 2.0? (android)
I see, I just wanted to ask if there was another method that doesn't require creating a new class
there isn't, yes
You also can do this using IntNode = Node<int>; I think (from what I could find on internet)
oh, well, yeah, that's helpful, thanks
Hello guys.
I'm making some AI for my enemies, and i thought i would be a really cool idea to have a MonoBehaviour that instanciates a regular C# object for the enemies Behaviour. The C# object would be serializable of course and it would be easy for someone to change behaviour specific variables on the inspector for the MonoBehaviour script.
so.. for instance:
public enum Behaviour
{
Chase, Patrol
}
[SerializeField] private Behaviour behaviour;
[SerializeField]private AIBehaviour currentBehaviour;
private void SetBehaviourSpecificData()
{
switch (behaviour)
{
case Behaviour.Chase: currentBehaviour = new FlockLikeChaseBehaviour();
break;
case Behaviour.Patrol:
default: break;
}
}
So basically it means running the SetBehaviourSpecificData function in Edit Mode, is it possible to do something like this?
You could run the function in OnValidate. You could also add the ContextMenu attribute to the function, though I think it needs to be public. The latter just creates an option to run the function in the 3 dots menu of the component in the inspector
Uhm... On validate isnt really doing anything as far as i can tell. I dont really have the custom C# object showing up on the inspectorº
Usually, behavior are made with a graph of ScriptableObject.
Also, note that you cannot use SerializeField for polymorphic class. You need to use SerializeReference (And you need to have an editor tool to be able to manipulate it as Unity as no built-in tool. Something like https://github.com/mackysoft/Unity-SerializeReferenceExtensions)
Finally, the pattern you are using at the moment is called Strategy Pattern. There is a ton of resources online on how to implement it in Unity. https://www.google.com/search?q=unity+strategy+pattern&oq=unity+Strategy+Pattern&aqs=chrome.0.0i512.5768j1j7&sourceid=chrome&ie=UTF-8
Awesome!
The github package your linked works as i expected.
I'll definitely research a bit about the strategy pattern, thanks!
Hello,
I have made a common "Enemy" script assigned to an enemy where if the player is inside a trigger which is above the enemy, the enemy will not move. When I add multiple enemies into the scene with the same "Enemy" script, it works fine except when the player is above one enemy, all other enemies will also not move. How can 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.
would you like the entire enemy code or just that specific part?
Everything
ok, it is over 100 lines of code tho
Not an issue.
Read the bot's message
ohh
We will need the player script as well.
in the enemy script, the isAbove function is checking if the player's is in a trigger, any trigger
This is because the enemy looks if the player is in trigger without checking if the player is in the trigger of this particular enemy.
isAbove() checks if the player is in a trigger
exactly
You want to do the check on the enemy side
yes i managed to see that too but im not sure how to go about making it unique to one enemy
make isAboce return istouching, as an example
The enemy must check if it is above the player, not the player if it is above an enemy
or just erase it and check IsTouching alone
does the trigger have any other functionality?
I would use https://docs.unity3d.com/ScriptReference/Physics2D.CircleCast.html in the enemy.
no, but there are two triggers in the game
one is for isTouching and the other is for isAbove
they are both in a separate layer so they dont collide
seems to me like you're making this harder than it should be on yourself.
But yes, you can make another function for the isAbove trigger
thats pretty good for a first time, keep it up!
In programming the pattern to program towards interfaces is very popular, but should I also use it in unity, or in other words, should I try creating an interface for every class that may be accessed in code, so that the class can be accessed via an interface, even if I could as well use the class type instead?
It's OK to use interfaces in Unity, but you should do it if it's appropriate to your need. It's common to see interfaces in cases like IDamageable for example.
Alright, so I guess I should use interfaces for classes that share common functionality then. Thanks!
Exactly 🙂
I can't wrap my head around sub assets, scriptable objects of custom type and custom asset importers.
I want to have:
- a custom class Graph that is
[Serializable](but contains non-serializable data such asHashSets, so I have to somehow serialize it yet I don't know how for now) (Already have that) - an asset of type
something.graphwhich holdsGraphclass instance and sub-assetsmaterial.matandshader.shader. It should serialize the material and shader - when I create the asset (scriptable object has
[CreateAssetMenu]) I want to create sub-assets for material and shader - I want this asset to display like that in the assets:
How do I do that?
Assets\Scripts\PullPlayer.cs(9,13): error CS0246: The type or namespace name 'PlayerMovement' could not be found (are you missing a using directive or an assembly reference?)
public PlayerMovement movement;
What am I doing wrong?
What is PlayerMovement?
a script
I assume yes, but where is it defined ?
This is defining it i thought:
public PlayerMovement movement;
Does that script exist
Yes
Well I would check again because it cant find it
I litterally have it open rn lol
It doesn't define the class
It declares a variable of type PlayerMovement, ok, but where do you define this class ?
Ohh the class? it's defined in the player movement script:
public class PlayerMovement : MonoBehaviour
Do you have any other compilation error in your console ?
Nope
Is PlayerMovement a class you defined yourself or is it from a package ?
It was a script from the first person template that I renamed
Did you rename the file as well ?
Yes
Is it contained in a namespace ?
Yes, but I tried doing:
using StarterAssets; and that didn't change the error at all
Is by any chance this scripts stored in a folder called StandardAssets ?
Nope, it's in a folder named Scripts
can you share the !code of PlayerMovement please ?
📃 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.
Yeah you have the right namespace and all
I'm kinda out of idea here
Try closing and reopening unity, sometimes errors are hidden and show after a restart
Yeah i have no idea. I'm referencing another script the exact same way in my script with no issues
Alr lemme try that
Nope still there
im trying to use customize unitys character controller to walk smoothly on any surface, at the moment ive ran into an issue where the character has no problem walking along the worlds z axis but when walking along the x axis as soon as the player hits 180 degrees the x axis input inverts and im not sure how to fix this, i was hoping if i sent someone my code maybe they could have a glance at it or just any advice would help
fixed it. Instead of doing using StarterAssets;
I had to actually make the script a part of the same namespace:
namespace StarterAssets{}
That's weird, but fine
Character Coontroller is not made for what you are trying to do. You should implement your own controller.
true but im just trying to figure out whats not working at the moment
If you did StarterAssets.PlayerMovement it should work fine
Anyway, you fixed it and it's the most important
Because it assumes that the player always move with the Vector3.up has the up direction.
Yeah now my script is doing this:
NullReferenceException: Object reference not set to an instance of an object
StarterAssets.PullPlayer.Update () (at Assets/Scripts/PullPlayer.cs:34)
PullPlayer:
https://gdl.space/ujunagopip.cs
I tried dragging the player with the script attached into the variable slot but I can't
You need to assign your movement variable
Ah
so my approach isnt wrong the character controller is just fighting against me?
Yeah I'm kinda confused lol
The character controller is not made for that. So yes, it fights agaisnt you.
Can you show the inspector of the object you're trying to drag into the slot ?
Does the player GameObject have the Movement script on it?
I have read it, but I want to create fresh shader and material when asset is created. Should I be doing it in the OnEnable of my ScriptableObject, or maybe I should avoid using [CreateAssetMenu] and use [MenuItem("AssetDatabase/...")]? But then when I write a ScriptedImporter where do I assign the shader and material to the asset? I can't conceptually grasp what the main object of the asset is and how I write some serialization/deserialization for that
It's called PlayerMovement but yes
Is it the right PlayerMovement ? Like, if you double click it, is it the script you shared earlier ?
for example why do I need to add a when creating a material asset, that should be a sub asset of my SO
Is there another script called PlayerMovement?
Yes it is
No
No idea what you are talking about. You do not need to write any serialization for a shader or scriptable object ?
but i still dont understand specifically why it assuming to move with Vector3.up would affect it in the way ive described/shown, why move completely fine on one axis and not the other
I want my custom asset that looks like something.graph and it basically looks like that:
class SomeGraph : ScriptableObject {
Graph graph;
Material material;
Shader shader;
}
and I want the shader and material to generated automatically for that asset. They should not exist by themselves
just like shadergraph asset has it's own material
When you generate the mats, shader and graph you just need to add it as an asset with the function I gave you.
There is nothing else to do.
Something like that
MyObject.Shader = myAsset;
AssetDatabase.AddObjectToAsset(MyObject, myAsset );```
oh, so I don't need to create material and shader with the AssetDatabase, just use new Material() and add it to the asset?
I mean, you need to create the asset on the disk as well.
new Material() is only memory.
this fixed it:
movement = player.GetComponent<PlayerMovement>();
So the inspector accept a gameObject ref but not directly a component ref... well
I'm puzzled, but glad you fixed your issue
Yeah I am too lol
these problems don't make sense. Something else is wrong.
don't know if i'm in the right thread but, my level looks fine in blender but when putting the same file in unity a lot of textures don't show, there are some visual glitched etc as you can see. someone help pls?
not a code question
what is the right thread?
#💻┃unity-talk or #🔀┃art-asset-workflow
looks like it could be the backface culling issue
Also check for flipped normals
Yeah but it's hard to pinpoint the problem without accessing the actual project
don't know how to
tbh don't even know what that means, i'm kinda new to 3d unity
There's a pin in #🔀┃art-asset-workflow regarding it. You can continue the conversation there.
I was just linking the fact I mentioned it.
@swift ocean
What happens if you find in a position where your randomly generated map cannot fit the constraint you made ?
Wave Function Collapse / Other procedule generation methods -> Thread
so i have this piece of lines where i get the 4 audioclips from the resources folder however when i play only the first one is found. Spelling is correct, paths are correct. once i disable the first line then only the second one is found. any knows what is causing this?
what do you mean by "disabling" them?
When are you running this code?
Show the files in their folder?
disabling as a check so '//'
so it becomes green, just to check it
running the code in update
you mean commenting.
why? Just grab the references once in Start or Awake
or if you're hardcoding the paths anyway, why not just directly reference the things in serialized fields?
Anyway what makes you think it's not finding the others after the first?
oh thats called commenting thanks
i did it in start and awake but then it finds none
not even the first one
i want the inspector to be a lil cleaner
how do you know?
because it finds none
So you already have these fields in the inspector?
How does this make the inspector cleaner
you can just assign them here
yes and i want to get rid of them
oh gosh
📃 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.
My moonshot theory - you have something like if (WeaponShoot = null)
ye im using pastebin is that fine?
yes
please dont hate on my coding style im trying to clean some up rn lmao
that's not pastebin
huh
I'm on a work computer can't download files really
so I can't read that
please post to a paste site
oh how can i do it otherwise?
!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.
ive always used that
like the link?
upload to the paste site and share the link here, yes
https://hatebin.com/dsbzseuvtz like this?
well thats a new way
So when you run the script these fields don't get populated?
correct
Can you try:
WeaponShoot = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeFire1");
WeaponAimIn = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload3");
WeaponAimOut = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload1");
WeaponReload = Resources.Load<AudioClip>("WeaponFolder/Audio/RetrofitEscapadeReload7");
if (WeaponShoot == null) {
Debug.Log("WeaponShoot is null");
}
if (WeaponAimIn == null) {
Debug.Log("WeaponAimIn is null");
}
if (WeaponAimOut == null) {
Debug.Log("WeaponAimOut is null");
}
if (WeaponReload == null) {
Debug.Log("WeaponReload is null");
}```
sure
i have no one clue of what you changed
but somehow it finds all of them now
you littarly used debugs and it works what the hell
maybe it was an issue of the script not being saved? IDK
i been trying this for the past hour, and have changed and saved this many times
i removed the debug and the lines are on the exact same spot
and now they are all found
thanks for the help!
as always
🙂
yes i will next time upload the link for everyone : )
don't crosspost
If I want a prefab that exists in world space (a sprite renderer) but I want some components on it to be rendered in UI space (like a slider or some text).. how would I do that?
(When I try to create a UI element on a non-canvas prefab, it adds a new canvas to the prefab)
worldspace text..?
I've put a canvas on my prefab and a text under that, but it doesn't show up in the scene (and I can't do layout in the prefab editor since it's in UI scale - ie, it's huge relative to my sprite)
i get one of these things where the sprite is tiny in the lower left
and the text doesn't render at all in the scene:
If I have to make two separate prefabs, one that's the "world" prefab and another that is the "UI" prefab (to show things like hitpoint sliders, name of the unit, etc) I can do that, but that seems like it's the wrong way to do it
quick question I am getting this error in my code. error CS0117: 'Noise' does not contain a definition for 'GetNoiseMap'. (here is the line for the code) noiseMapTexture = Noise.GetNoiseMap(width, height, scale); Does unity not have a base Noise? Do I need a using for it?
I have it working if I set the canvas size (on the prefab) to 0 and the tmpro size to world space size.. but this leads to font sizes in world space, which is .. odd. Is this how it's supposed to be done?
Can anyone tell me why label at sprite resolver isnt being set to "Entry" from "Entry_1"?
after i set the label, i print it, and it says its "Entry"
but the sprite resolver still says its "Entry_1" as shown in pic?
I guess you're referring to a different SpriteResolver than you think you are
or the label is changing at some point between the inspector being drawn and the code running
it printed colour red for
sprite renderer, so its the right resolver, coz its the only one whos sprite render is coloured red
That's not exactly convincing
How about:
Debug.Log("Click here to see which resolver i'm referring to", resolver);```
when you click that log it will take you to the object it is referencing
when you click it it highlights that one in the hierarchy?
when i click any of the prints, nothing happens probably coz im on mobile 2d unity?
like usually if i clicked on print, it would bring me back to code where it was printed but nope
I don't think you put the same code as I did
for your Debug.Log
especially if you're using print and not Debug.Log
yeah that's not what I wrote
there's a very specific reason I did it this way
ah
it's so you can click on the log and it will highlight the object
Ohhh, i thought print allowed same thing no?
print doesn't have the overload with the second parameter that my code is using
ok good
so then the only remaining possibility I guess is that the label is changing
or maybe your GetLabel() function is doing something weird
what does GetLabel() do exactly?
its only getting "Entry" as the label
can you show more code
well, gets a certain LABEL depending on the towers health, and then the label is slightly different if castle is level 1
but i have put a print in this code before, and its shown to print at return "Entry"
ok so this code has nothing to do with the "label" field in the inspector
so then looks like the health percent is >= 0.7f and the current castle level is level1
like thats the full code if u want to see
current castle level is 2, and yes its above that
you sure? Prove it
add more logs to GetLabel()
Well it prints "Entry"
right
if it was 1 it would print smth else
that clearly implies level is 1
oh right sorry
NOT level 1
yeah
so that's the reason
that's what the code tells it to do
I don't see what the mystery is here then
Yes, it returns "Entry", which is the label that the sprite resolver should have been set to
but it hasn't
its still at "entry_1"
because you're calling a completely different function to set the label
GetLabel() with some parameter
not the same thing as resolver.GetLabel()
maybe you just wanted to call resolver.GetLabel()?
i know that, no nope, getLabel is my custom function, to get a label depending on health
which returns "Entry"
which is good
the problem is that resolver label hasnt been set to that
and i dont know why, after i set it, i print it and it says its "Entry" but not in inspector
can you show the code for this other GetLabel() function?
and also what SetCategoryAndLabel does?
that's a different GetLabel function
Btw could it be that
oh I see this is the one with the parameter
could it be because the bottom two categories
have similar named... entries
or not mhmm
so is thia bug thing
I don't really understand what it is or does
One final thing i could do
is manually assign sprite renderer in some variable
and then check that sprite renderer to the one in code and see if they are same?
but tbh maybe theres no point in that
i will report this bug to unity, see if thye can fix it, coz idk
Ask an actual question and find out?
well heres the code
it rotates only on horizontal, and some of the inputs are disabled
look very closely at your VerticalRotation and HorizontalRotation methods
ok
but the model keeps tumbling around even though ive applied all the rotational constraints
pls help
if anyone could send back a revised version and explain why it went wrong that would be helpful
I'm thinking about Physics2D.OverlapArea(), but I need to know the most lightweight way to do this for my game. I specifially only need to know if there is AT LEAST one collider of a given layer in a region. I need to stop the computer from doing extra work if there are 200 colliders matching that description.
is OverlapArea the right method for this?
i don’t need to know what collider is there, nor an array/list of them. Just a bool
well, OverlapArea method has a layerMask parameter
but it should be ok to use it if you just want to see any collider in the area
you can also use OverlapBox
Did you find anything wrong with the two methods I pointed out?
i did, the mouseX and MouseY were added to the wrong components
am i wrong
They both did the exact same thing
yeah
i actually realized that i kept a backup of the project before i started using the new input system so its all good
even though it would mean 2 hours of work down the drain
😭
well thank you so much
ill try to rewrite it a bit more meticulously
how do I add this script to the GameObject?
public class OptionSelectButton<T> : MonoBehaviour where T : Component
to add a script to a gameobject, u clikc add components and then type name of script
or drag and drop
the script from its place in explorer to the inspector tab
cannot add a script with generics via the inspector
well.
it just shows "OptionSelectButton"
yes thats the script
oh, no, it doesn't show anything
I have removed overload.
I just cannot add it
I have messed up with the package that should have controlled this thing after I have deleted it
so.. no T with MonoBehaviour?
you can but you must add it via code so you can specify a T
Or create a concrete type that inherits from it with the type parameter specified
not comfortable too.
anyway, I will have to create a few of them
and it will throw an error
Well those are your options with generic MonoBehaviours
I see, generic MonoBehaviour sucks.
What's the best way to create a queue of an arbitrary type?
It's mind boggling that List doesn't have a Pop function
I tried the c# Queue type but it thinks I want to fill it with objects, not my custom class I want to fill it with
Queue<MyType>
Hello, I'm trying to make an Android app that measures the device speed with an accelerometer, but I have a small issue. I have successfully acquired the accelerometer data and removed the gravity, but it doesn't appear to show deceleration. It shows acceleration and I'm able to calculate speed based on that but it doesn't decelerate. My current code looks like this:
Input.gyro.enabled = true;
Vector3 accel = Input.acceleration - Input.gyro.gravity;
Or Queue<object> if objects is really what you want
Nevermind, turns out I just needed to explicitly cast the Dequeued thing back into my type
For sure, but you should try to have common interface or base type you can abstract
How does Physics.OverlapSphere work? Physics.OverlapSphere(transform.position, 6.0f, 1 << wallLayerNum) is returning an empty array when I'm definitely within 6 units of a wall
Are u working in 2d or 3d?
2d
oh do I need to do overlap circle
or something
yup, there we go, Physics2D.OverlapCircle
hrrrrrm
So I've got an object on a 2d playing field, and I want to be able to quickly check what parts of the playing field that object can "see" without other objects in the way. Problem is, raycasting is... pretty expensive
Are there any fast alternatives that might work under certain circumstances
Raycasting is cheap
It definitely does not seem cheap when I need to do it dozens/hundreds of times per check
You said this but is it for rendering? Or something else
A single overlap circle and math could essentially give you the same result
I am trying to create a tree for an AI that predicts player location with a series of nodes. First I raycast to the player, if I don't hit them I can't see them. Then I need to check each of the leaves to see if the AI can see that leaf from its current location, and if it can then the player is obviously not there.
I'm not sure what you mean
Not sure I understand the tree part here. Why isn't the original Raycast sufficient?
"IT" is my agent, white is my player, green is player's last "known" position
white is a tree of locations I predict the player could be based on its movement speed
You can either see the player or not
I don't understand how predicted positions relate to a line of sight check 🤔
Yea sorry I dont really understand where all the raycasts come into play either
I'm not just checking if I can see the player, that's a single raycast, I'm checking if I can see each of these nodes in the white tree
Why do you care if you can see the other nodes
Because if I can see a node then I know the player is not there
And I should remove it from the tree
In this second image though why weren't most of these nodes removed a long time ago
Why would they be, I can't see any of them, the player could be in any of those places
I am creating a bot that predicts a hiding player's location and tries to look for them. It cannot and must not simply know where the player is through perfect information or there is no capacity to hide from it.
I can't help but feel like this is more of a pathfinding problem than a raycasting problem somehow
Maybe you're right but I'm not sure what to do
I think u are kinda creating the problem yourself.
You shouldnt make a node then have to filter them out, dont create the node in the first place if the ai can see it
I'm doing that, but the AI's vision changes over time
Btw you can also use RaycastCommand to do a lot of Raycasts quickly with the job system
mmm
I'll look into that
like, ok, ideally, I would have some sort of continuous heatmap, update each pixel by factoring in nearby pixel's "probability" scores, remove pixels the agent can see at any given frame and add pixels the agent can no longer see
but there are no continous data structures
and I can't easily check each pixel for "visibility"
This will probably be too much to actually do if you ever have a couple of enemies
Well, right now I'm just focusing on one... It doesn't even have to be super performant I can prerecord the presentation for class I just want it to work fast enough to not crash unity...
and I don't actually need pixel accuracy
I just don't want a fixed grid because that is really bad for taking into account diagonal normalized movement
What's the goal for this though? This seems a bit overly complicated to have an AI reach the player
The point is I don't want it to just go straight for the player
It's a game of hide and seek tag
if you can't hide, then what's the point
maybe it is overly complicated, hell it almost certainly is
I just want to, without knowing where the player actually is, create a prediction of where he might be and go there
Well your AI does know where the player actually is, if you're raycasting to it all the time
I'd say it's easier to give an AI all the information then add in stupidity to it, instead of limiting information and trying to make it super smart
Mostly because the latter isnt cheap to calculate every, especially not every frame
I guess I'll spend some time thinking how I could do that
I also don't need to do this every frame
https://hastebin.com/share/kuhebikene.csharp I've been having this issue where when I kill zombie while also getting hit by the zombie, the effects still play and my health doesnt regenerate. When I looked into it, all I noticed is my isTouchingEnemy and isTouchingPlayer boolean stays set to true.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
https://hastebin.com/share/iwuquyavoq.csharp here is the other script that includes effects
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So basically, say I have two Positions/Transforms, how could I find out if a positions is in the min/max area or if it is between the two other vectors? (the areas are basically perpendicular to the path of the two positions...)
This was a fun problem, hopefully the drawing makes sense
A) Let’s figure out if it’s to the right of the min.
- Get the vector from min to max
max.position - min.position - Next get the vector from min to target
target.position - min.position - Compare the Dot Product of the two vectors. If It’s greater than 0 or equal to 0 then it’s in the zone.
B) Let’s figure out if it’s left of max - Get the two vectors, then dot product it to figure out if it’s in the zone
Dot product returns 0 if the two vectors are perpendicular, positive if it’s closer than perpendicular, and negative if it’s further than perpendicular
https://twitter.com/FreyaHolmer/status/1200807790580768768
Wow, thanks a lot, i'm sure i'll be able to implement it now!
Check out the gif, it’ll help you see it. End result will look a bit like
bool InZone(Vector2 target, Vector2 min, Vector2 max)
{
Vector2 minToMax = max - min;
Vector2 minToTarget = target - min;
float a = Vector2.Dot(minToMax, minToTarget); // dot product
if(a < 0) return false; // we know that the target is behind min if it’s negative
Vector2 maxToMin = min - max;
Vector2 maxToTarget = target - max;
float b = Vector2.Dot(maxToMin, maxToTarget);
if(b < 0) return false; // target must be behind max
return true; // true if target is in the zone
}```
yep, that's how I just finished it up, thanks a lot for the help!
me needs help
would collider related questions apply here?
I have disabled gravity in my top-down 2d project, because I dn't plan on using it and it was causing problems with the player falling through the floor.
I got the colliders to work with the in-game objects like enemies, walls etc. However, **now that I am trying to add isTrigger = true on the Boxcollider 2D, the collisions no longer work and the player passes through the enemy. **I see the collision trigger register in the console, so I know it is working properly. Any ideas?
Suggested answer: Don't use a trigger, use the OnCollisionEnter2D event instead?
The OnCollisionenter2D method isn't being called when they collide now... so that's an issue 😦
It works when the enemies collide with each other, but not when the player collides with the enemy. No clue what the issue is. The player is moving with rb.MovePosition which should be ok I think?
Player rigidbody (img 1)
both enemy & player have box colliders, but the enemy doesnt have a RB
Trigger does not register a collision with an incoming rigid body
It only serves as an event trigger
Is the other collider also a trigger?
this is really a #⚛️┃physics question but you're using a kinematic body
no, i have disabled the isTrigger on both
kinematic bodies don't really collide with static objects
Ah, yeah, that's a kinematic body lol, didn't see the screenshot
i tried changing to DynamicBody and had the exact same issue, except physics was applying in some way to the objects
collisions are working, but the OnCollisionEnter2D method is not being called
show the inspectors of both objects you expect to be involved in the collision
and also your code
box collider for Enemy
just show the full inspector for each
uh there's a lot of unrelated stuff in there
ok well I'm interested mainly in any collider2Ds and rigidbody2Ds
yes, the enemy doesn't have an RB at all.
Player has the RB I showed above, and the player's Collider looks like this
the enemy, if it's moving, should have a Rigidbody2D generally
yea its not moving atm
basically to have an OnCollision2D, you need:
- one dynamic Rigidbody2D
- each object with a NON trigger Collider2D
right that was my understanding as well, which is why i'm confused that it isn't working
could it have to do with player movement?
where are you calling the code, on player or?
on the enemy
then he needs a rigidbody i think
the caller of those events need to have rigidbody i believe
player movement code is
rb.MovePosition(rb.position + direction * moveSpeed * Time.fixedDeltaTime);
ur movement code is irrelevant here
just add rigidbody to your enemy and test it using debug.log
the enemy was triggering collisions if they spawned on top of each other... so
Show the whole script
they can interact with each other
that means it was working.
this is also not really a movement mthod that respects collisions
need help
should move via velocity
it will still call oncollision event no matter
let me try that, I think that's the issue
MovePosition with dynamic body would only make it weird when colliding, but should still trigger events, no?
yes
I mean... probably but it's weird
Yeah, would be better to see the whole script
we haven't seen the code yet so there might be something wrong there
!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.
u need to check for tag on collision
make sure its called only on player collision with enemy
sorry which code do you want to see? the whole playermovement script?
he wants to see oncollision code
whichever script has OnCollisionEnter
u need to check for tag
of what object is he colliding with
using CompareTag() method
thats why u had issue of
is passing a parameter with in not passing by reference? I thought in was just ref but the function cannot reassign what that parameter is?
in out and ref all pass by reference
yeah this looks fine, should show up in the console
very strange then indeed. I have a struct that appears to be coppied when passed with in, but not when passed with ref.
show the code and explain what's going wrong?
it wont because he removed rigidbody
well yeah if you remove the Rigidbody2D it won't work
he doesnt want to set it back on because it will run when enemies collide
I'll have to ask in DOTS chat I believe, it's the unity.Mathmatics Random struct.
i didn't remove the RB, it's on the player
Adding one to the enemy does not fix it either
u need RB on the enemy if that OnCollision event is on enemy
From a posted related problem
"Hi, if you do the destroy in Update() instead of OnCollisionExit() there's a chance you'll have the grounded flag true from picking up the second collider.
However, you could have cases with a racing condition causing the flag to stay false.
To go arround it, you could instead store in a list all the colliders your ball touches at any given time in OnCollisionEnter, remove them from the list in OnCollisionExit, and check in Update wether you've got at list one ground collider in list or not.
Additionnally, this method has a major flaw that on rare occasion you wont get the OnCollisionExit, it happens sometimes when there is a lag spike and you can't do anything to prevent it (as far as I know). So what you need to do is check if your player still collides with colliders in list, if your objects are axis aligned then it's a really simple and efficient bounds.contains() check.
You could also consider raycasting/spherecasting to find out if your ball is grounded."
Passing Random in with in seems odd since almost all the functions on it will mutate it
yes it will
burst complained it wasn't passed by reference
If you want to see in a screenshare I can, but you're wrong
sure let me see
in creates a defensive copy probably in this case
since you are likely mutating it with a function call
yes, however i thought that was allowed when passing with in
i dont see voice channels do we need to go to a private server?
I've done it with lists for example and i can still add things to it. But that's a reference type, so i suppose it can work different with value types
idk never used screenshare here
yes lists are references
very different
but we dont need to use it to fix it
Try checking if the enemy is destroyed on the CollisionExit too
in is specifically designed to prevent you from changing it
ok well I promise you, I just added the RB to the enemy, it didn't change a thing. The player already has one
do they collide?
yes, they've been colliding all along, that's not the issue
the issue is the OnCollisionEnter2D method is not calling
so in the case of value types it creates a defensive copy? Thanks for the link btw! I haven't heard of defensive copies before.
only if you call a function on it
are ur rb kinematic?
Interesting, thank you!
because the compiler can't guarantee the function won't mutate the object
if all you did was read a field, you would be ok
and this is only for value types, right?
yes
awesome thanks
so? are they?
You were 100% right, changing it to Velocity fixed it. LMAO
totally had to do with player movement script
cool. Yeah MovePosition is generally intended for kinematic objects
ty sir (or madam)! you're a scholar, and ty @swift falcon for trying to help, I appreciate it
is there anyway I'd achieve this with kinematic objects instead? I'm not even sure I want to respect normal physics in my game necessarily
Yes, but you would have to write your own collision detection
I have a script if you want to
im interested. I guess I need to think more on if I want to go that route or not. I mean, generally it's gonna be an oldschool RPG feel where if you run into an enemy, it triggers a new battle scene. so in that way, i'd think kinematic bodies would be a better approach. thoughts?
Well, it makes the movement script way more complicated
I guess I could just make the enemies have a LOT of mass, right? and basically the same effect?
However, it makes it more customizable
If you don't have many custom things you want to do, generally using dynamic bodies and just disabling gravity is simpler and works
I'll send you my script and the explanation.
May I dm you?
absolutely, I appreciate it
is it me or is it too confusing? anyway i was trying to make monitor fps counter and decided to put TextMeshPro on UI Screen, fps counter on UI works but the error is bothering me, its gotten become more annoying when i was trying to fix this
just in case its working but the error is still here
nope, i just tested it, u just realised u didn't change it to non kinematic.
id start by turning on error pause then looking at the first error
MovePosition works for collisions just aswell, thats kinda trashy of you to lie just to avoid saying thanks but im not gonna interfere. you do you, just dont share misinformation intentionally
i did say thanks, you kinda have a shitty attitude bro! but it's all good, have a nice day
nah u lied saying its addforce is what fixed it for you when it was really setting its kinematic off
yes, I'm a liar and a cheat. not like it was a misunderstanding or anything! you win
im not sure what are these, im assuming i should turn on error pause?
Its all good im just putting it out,no bad blood
yes turn on error pause so you can see the first thing. Also you can step through with the debugger to see whats really null
itll be more clear then

What a twist
do you mind telling me where to enable the error pause?
its right on your console, at the top
Hello, is it possible to drag and drop from a custom script window to the Unity editor? I want to drag items from a UnityEngine.UIElements.ListView to a field in the inspector. My ListView is populated with VisualElements, I need to somehow get the object each dragged element is referencing outside the window and into the Editor, then entered into my desired component field on release.
here you go
again, still confusing tho
hm do you have 2 instances of this script?
this one you're talking about?
you probably have another copy of the script in the scene
oh you're right
thanks
i probably accidentally copied of the script without even notice
i was wondering if theres a better way to do this or some way to fix it? i added the && !m_FacingRight and Flip() to make it so that the empty attached to the player for a shooting point flipped with it but now the running animation wont play. Sorry if this isnt where this goes
I don't see where or how this code really affects your animations. Also !code for sharing
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I'm doing a velocity over lifetime in a rain particle system (see picture 2). Therefore I'm using the "random between two constants". When I try the following code, the first of the constants are modified (the rainVOLT.xMultiplier works), but for the rainVOLT.x (or z) Unity says "Particle Velocity curves must all be in the same mode"...
Also after applying the .xMultiplier, it's not random between 2 constants anymore (see picture 1).
rainVOLT.x = windDirection.x;
rainVOLT.xMultiplier = windDirection.x + 10;
rainVOLT.z = windDirection.y;
rainVOLT.zMultiplier = windDirection.y + 10;
is your runing animation moving your character?
and do your other animations work when flipped?
show more code
We don't know what rainVOLT is
thats the velocity over lifetime module
rainVOLT = rainParticles.velocityOverLifetime;
and what is windDirection?
show more code please
not one line at a time
just a vector 2, it isn't necessary for the problem i think
it is
definitely necessary
key part lol
thats gonna take some time, give me a sec
by doing this:
rainVOLT.x = windDirection.x; that assignment is going to set the MionMaxCurve to "single constant" mode
with what properties do I set both the values for random between two constants?
you would need to do something like:
MinMaxCurve xCurve = rainVOLT.x;
xCurve.curveMin = something;
xCurve.curveMax = something;
rainVOLT.x = xCurve;```
my bad oleex didnt notice u set it to y
no worries but thanks ill try that ^^
wouldn't the xCurve make the velocity adjust to that one curve all the time?
I'm trying to get it in random values
can u set xCurve.curveMin to some Random.Range?
this code will do random values
assuming it was already in that mode
Since we didn't modify the mode
is it random for each particle, or the same random value for each one?
random for each I assume, but this code is not changing what it was before
ohh i c