#archived-code-general
1 messages · Page 188 of 1
poco
plain old C# ...? lol
ah i never heard that term before
public class InventorySystem
{
private Item[,] _inventoryItems;
private int _width, _height;
public InventorySystem(int inventoryWidth, int inventoryHeight)
{
_inventoryItems = new Item[inventoryWidth, inventoryHeight];
_width = inventoryWidth;
_height = inventoryHeight;
}
public bool TryAddItem(Item item)
{
for (int i = 0; i < _inventoryItems.GetLength(0); i++)
{
for (int j = 0; j < _inventoryItems.GetLength(1); j++)
{
if (_inventoryItems[i, j]._amount == 0)
{
_inventoryItems[i, j] = item;
return true;
}
if (_inventoryItems[i, j]._amount < _inventoryItems[i, j]._maxAmount)
{
_inventoryItems[i, j]._amount++;
return true;
}
}
}
return false;
}
working on an inventory system, currently I have this underlying data structure / helper methods class that I initialize inside a monobehaviour, and that MB also has a second multidimensional array to bind the data to an ingame inventory UI which has a grid layout group of "cells" for each inventory space. I'm not sure how I can get references to each inventory cell in a deterministic way so each cell correponds to the i and j values of the multidimensional array. My first thought was to use an empty component but I'm not really sure how to make that work. How do you guys deal with this problem?
GetComponentsInChildren uses a DFS algo right?
Create a script on each cell that has a reference to an inventory slot.
public class UIInventorySlot : MonoBehavior {
[SerializedField] private int slot = -1;
public void Initialize(InventorySystem inventory)
{
inventory.GetSlot(slot);
}
}
Also, I do not think you should use a multidimension array for your inventory.
This is only a concern of UI.
i have an issue trying to serialize a generic class:
[Serializable]
public class IntProp : TranslationProperty<int>
{
}
[Serializable]
public abstract class TranslationProperty<T> : TranslationProperty
{
[field: SerializeField]
public T Value { get; set; }
...
}
[Serializable]
public abstract class TranslationProperty : ScriptableObject
{
[field: SerializeField]
public string Name { get; protected set; }
...
}
I dont know why it is failing, i created a test using a IntProp and the serialization fails.
public class TestTranslation : MonoBehaviour
{
public IntProp prop;
}
when i set the value, the value is reset when i press play button
i tried removing abstract but doesn't work
Help with UI Sliders
not sure if this belongs in code-general but, a long time ago i noticed that my game is super laggy for the first few frames, probably because everything is loading, and the framerate is unstable. So I implemented this method where I wait a few frames until everything is stable and then run everything game related, and I still use it to this day. Is there a better method? This is out of pure curiosity and not urgent, but it also sprung to me that my constant value of 10 frames might not apply in every situation.
You can use addressables to load assets asynchronously to reduce the lag spike.
Or you can use a loading screen, which goes away after a couple of seconds, so the lag would be unnoticeable.
Hello every one.
Culd anyone help me?
I want to integrate stockfish api to unity and build it to android platform.
How can i do it?
Please help me if you have experience with it.
you mean the chess engine?
Hi, I want to add multiplayer to my game, I searched the internet but couldn't find an example which has a separate client + server for netcode. Can I have both code in same project and somehow build the server separately as a dedicated server built?
I don't want the serverside code into my client build.
Yes.
Hi im trying to pick up an AI that moves using the navmesh in vr. for some reason i cant pick it up with a collider attached as it just wont lift off the floor (assuming its cus the ai doesnt see it as moving land) so i have a code to turn the navmesh off and collider on when a trigger collider is triggered, but when it activated, the ai just falls through the floor
show inspector for the ai and relevant code
yield return new WaitForSeconds(value); but inside a Coroutine
inside the OnTrigger you call your Coroutine then
alr ill give it a try
Are you there?
Do you know how to use stockfish with unity for android?
not really
using a coroutine with a for loop and "yield return new WaitForSeconds(1.5f)" end of loop works for me, but I am getting some odd delay and the time seems off with inconsistent wait times... any idea why the time delay might be inconsistent?
I also tried WaitForSecondsRealtime with the same inconsistency
where inside the OnTrigger, cus i put it between the 2 and it still happend
show you new code
thats where i put it
my only other thought is turning gravity off on the ridgidbody attached to it while the trigger is activated, just so it doesnt fall
but before you had it in OnTriggerExit
Hey I wanna start developing a multiplayer mobile shooter, and I also wanna learn dots. Is that a good use of ecs and dots In general
Use precompile define in your code to limit what make it to the client build. Also, almost every network solution for Unity is made for single project and you should definitely use a single project.
?? i didnt have a corutien, there are 2. there is a triggerEnter for turning off the collider and off the agent, and then the opposite when the Trigger box is exited?
ohhh that
i messed up codin it
wasnt acc ment to b there
sorry
It originally looked like this
Thanks, does this also work with server build?
this had nothing to do with the coroutines, it had to do with animations transition delays . oops! anyway problem solved
I think I finally solved my one-way collision issues
the trick is:
- Need tilemap with it's own gameobject so all semisolids of that 1-way are combined.
- Make tile hitboxes thin, with edges terminating in a point.
- CompositeCollider2D with POLYGON mode
- PlatformEffector2D with one way on, and one way grouping OFF
Precompile definition (#if SERVER) is a C#/compiler functionality and work with every platform.
So you can have a keycode variable in the inspector, and you can select what key you want that variable to be set to, is there something like that but for xr controls
ah my fault
I have a code where I'm constantly changing my enemies and player character controller radius. If I do that when characters are already intersecting, they will go thru each other as if collision was disabled. What could I do to fix that?
use physics queries to check if the new sized obejct would overlap anything
Do you think CCD would work as well? Idk how that can be enabled for Character Controllers, tho
What would CCD on a rigidbody have to do with this? I assume you're just directly changing the scale, in which case you need to do as suggested and check if they can fit in the new area.
It's the same issue if you directly modify the position or rotation
What?
no
of course not
how would CCD predict your intention to rescale the object?
That was a question. If it doesn't work. Ok 🙂
It only knows about normal Rigidbody velocity based motion
In my specific case, I do have to resize character radius anyway
But what I don't get is why object acts as if there is no character controller collider at all, only by a small change in one of the objects radius
But I never had such scenario where I have two colliding character controllers changing their radius
I know changing a single character controller radius while trying to collide against non character controller colliders works just fine
Something like that invalidates the player x enemy collision and I can proceed to pass thru the enemies
When I am Despawning an In-Scene network objects I keep getting this error SpawnStateException: Object is not spawned Unity.Netcode.NetworkSpawnManager.DespawnObject (Unity.Netcode.NetworkObject networkObject, System.Boolean destroyObject) how do I stop this error even though its working properly
Just o answer my own question here: looks like by adding a Capsule Collider at the same Game Object as the Character Controller and setting both radius to the same value prevents the two Character Controllers to go thru each other when the radius changes
Sounds like overkill having two colliders per character only to do that, but it works...
#archived-networking or try the ngo discord pinned in there. That error is quite clear though, you are despawning an object not spawned, look at the network object component as this code runs
hello!!! i'm not sure what the error would fall under but i'm trying to run some old simulations a colleague made and I am getting the error of "Microsoft Visual C++ Runtime Library: This Application has requested the Runtime to terminate it in an unusual way" whenever I click run
and then it instantly crashes
Would anybody have any idea what error this could possibly be related to? Thanks!
I can slide only one enemy at a time
is there a good way to add a distorting effect or something to a spriterenderer? I have some fluids (like water layer) but they don't look very fluid
U can use shaders for that
Idk much about how but i know its fairly easy thru the use of shaders
can someone take a look at my thread
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer (typeof(NamedArrayAttribute))]public class NamedArrayDrawer : PropertyDrawer
{
public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
{
try {
int pos = int.Parse(property.propertyPath.Split('[', ']')[1]);
Debug.Log("Calling in namedArray: "+property.floatValue);
string fieldName = ((NamedArrayAttribute)attribute).names[pos];
EditorGUI.FloatField(rect, fieldName, property.floatValue,EditorStyles.numberField);
} catch {
EditorGUI.FloatField(rect, property.floatValue, EditorStyles.numberField);
}
}
}
For this code, how do I allow for values inputted into the editor to stay there?
ah
so where do i store it?
do i store it in the property variable?
seems like the answer is yes
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Ah I didn’t see those I’ll post there thanks
does the "Runtime" folder make files inside load at runtime?
I made a tree spawner and for a reason I can't figure out, the trees are spawning at weird positions. basically the script spawns a tree at a random position within a range, and shoots a raycast down to snap the tree to the ground, but for some reason the trees are only spawning near water. I have a LayerMask, so the trees can only collide with the land. Here is my script: https://hastebin.com/share/rivinonube.csharp.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Getting rid of the layer mask causes the trees to only spawn at a fixed y-coordinate.
is it because im using a mesh collider?
I am trying to access the button of my prefab when I instantiate it, I cant do in the scene view of the game so I need to do it via script but when I click on the button is does nothing it doesnt even change colour when I hover over it for some reason
is their initial elevation too short that they are spawning inside the terrain?
so it can only hit the water. (because it's lower )
sounds like you don't have an EventSystem in your scene
private void MyFunction()
{
Button InstantiatedButton = new_UI_Button.GetComponent<Button>();
InstantiatedButton.onClick.AddListener(delegate { MyButtonFunction(); });
}
public void MyButtonFunction()
{
Debug.Log("Button Clicked");
}
i did this but still not working
I have one
you sure about that?
if you did, your button should be working just fine. unless you've got a world space canvas and haven't assigned the camera to it
oh actually it has an error that I can fix
Where do you instantiate it?
nope fixed the errror and still not working
so the button is still not reacting at all to the mouse?
canvas is screen space overlay and I am using the third person assets
void AddCluesFromNoteBookToInterrogationPanel()
{
_InterrogationPanel.SetActive(true);
var entries = File_Handler.Read_From_JSON<Input_Entry>(fileName);
for (int x = 0; x < entries.Count; x++)
{
Transform parent = GameObject.FindGameObjectWithTag("Interrogation_Clue_Panel").transform;
new_UI_Button = Instantiate(ui_Interrogation_Clue_Button_Prefab, parent);
//TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
////variable text that accesses the instantiated gameObject
TMP_Text TheText = new_UI_Button.GetComponentInChildren<TMP_Text>();
//Sets the text.
TheText.text = entries[x].Clue_Description;
}
}
and by reacting to the mouse, i'm referring to responding to the mouse entering it and visibly clicking. not about the code
ah, still completely misunderstanding how variables work too
i'm no longer going to help you. please do some beginner c# courses to learn how to code
yh nothing I made it so that the button will change colour when I hover over it
Check the even system details at runtime. What does it show when you're hovering over the button?
nothing changed ?
this was the code that you helped me with I thought it was fine but thanks
i was using the following lines of code to handle serverside logic:
if (!isServer)
return;
unity ran an update and removed the isServer mechanic. can anyone help on what to change?
do i use the [Server] tag on the function?
No, the initial elevation is a good amount above the terrain.
it will also depend on what networking package you are using and whether you've inherited from the correct class
Log what it hits, and double check that assumption
never mind it was because of the third person assets I had it was messing it up with the mouse disable
For some reason it won't let me attach the "remote bomb" ablility to the current ability script.
It wants an instance of the class, not the class itself.
do you have an object with that component attached?
no, im trying to have a modular ability system
basically think of this system like spells or plasmids in bioshock
well that's why. it's a MonoBehaviour which means it needs to be attached to some gameobject to be a valid instance. and the slot in the inspector is expecting a valid instance
We know what you're trying to do
I cant do scriptable objects because that wont work with projectile abilities
Why wont it
because i would need the transform of wear the projectile is fired
Believe me i tried
You can pass any transform you wish i to it 🤷♂️
You wouldnt put the spawnpoint in the SO
you'd spawn the projectile at the spawnpoint when you're attempting to fire it
so GlassCannon.cs would have a slot for GunDataSO and spawnPoint
for an example.
this sounds like a use for the strategy pattern
I figured it out, the raycast was being shot from a y-coord of 0. So it was screwed up a lot. so I made the raycast shot from the same height as the spawner object, and it works. Now I just need to make it not spawn in the water.
Told ya 😎
I'm using OnValidate to call this method but it's giving me these weird errors:
void DrawTrail()
{
ClearTrail();
for (int i = 0; i < xAxisMax * pointDensity + 1; i++)
{
Vector2 pointPos = PositionCalculation(i / pointDensity);
GameObject spawnedPoint = Instantiate(point, pointPos, Quaternion.identity);
points.Add(spawnedPoint);
}
}
void ClearTrail()
{
if(points.Count > 0)
{
for(int i = 0; i < points.Count; i ++)
{
Destroy(points[i]);
}
points.Clear();
}
}
I don't think it's legal to call Instantiate and Destroy in OnValidate. You're going to jail!
What would I do then?
I'm facing this problem, I'll send a video
OnValidate is for validating your fields. Not anything else.
Hmmm
What you want is probably a script executing/updating in the editor
Thing is I have a lot of variable I need to keep track of if they change
And doing this for every one is exhausting:
//Updates the trail if something changes
if(currentPointdensity != pointDensity)
{
DrawTrail();
currentPointdensity = pointDensity;
}
You can raise a flag in on validate, but execute the logic in a normal update.
How would I raise a flag
Also you can do the same thing in update too.
sometgingChanged = true;
How would I unraise the flag though
Is there an OffValidate?
lol
After you update your graph:
somethingChanged = false
Now how can I make it only spawn on the non-water parts of the terrain, the water is a separate gameobject, so I tried giving it a layer, and making two layermasks, one for goodlayer and one for badlayers. these layermasks are added together to make the layers variable and that is used for the raycast, then I tried having it check if the layer it collided with was the terrain layer, and if so it would spawn a tree, but it didnt work. Here is my script: https://hastebin.com/share/yilogozegi.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What its doing instead is spawning trees no matter what layer it hit
if (hit.transform.gameObject.layer != goodLayer) this is certainly not doing what you think it is.
if you want to check if a layer is contained in a bit mask you need to do some bitwise math
int layer = 1 << hit.transform.gameObject.layer; //gets a mask containing only this layer
if(layer & goodLayer != 0) //this basically just checks if there is overlap in the two masks
{
//do your shit here
}
How are you expected to pass in the array results for Physics2D.OverlapCircle?
I.e. what sizing?
Do I just allocate an array once with the maximum amount of data I expect to go into it, then iterate up to the size passed back from the method call?
Exactly
Btw there's a List version too
If I have a instance of a Poco class in a dictionary, how can I retrieve it as a reference and not a copy?
Classes are reference types by default. You wouldn't get a copy.
Would having [Serializable] be changing that?
Ah I see that now- thank you! I take it the array version is more performant as its not resizing?
No.
What makes you think you get a copy?
yep, it gets re-populated every time you call the method. be careful, as you will have null entries if the number of colliders are less than its length . . .
Overlapcircle will return the length
Does it null out the array or just fill in the new entries? E.g. I overlap 3 colliders, then I overlap 1 collider into the same results array. Will index 2 be one of the old colliders from the first overlap?
true, but most ignore/forget and loop through the array without checking for null or using the current number of colliders . . .
for reasons I dont yet understand this causes any other items in the list to never exist, if the override is left empty the list becomes empty. How might I change this to add things to the method instead of replacing the method?
that doesn't replace the list at all. if something is clearing your list or assigning it to null, it's certainly not that
when this is not done the list works just fine, stuff gets added as normal
again, that does not clear the list. and cannot set whatever list you passed to it to null. so whatever is doing it is somewhere else
are you receiving any specific errors?
for clarity, I didnt mean its erasing the contents of the list, the override seems to be stopping any code the method originally had from running, like its running the code I put here but none of the original, which is not what I wanted to do, I want to run the code here in addition to the original
when this runs the list never gets filled with other things the original method fills it with
if you want the base method to be called too you need to call base.Setup() in there
like this, right?
depends on the order you want the code to be executed in, but yes.
I want the new code to run before the original since the original, at the end, gets the number of items in the list
then yeah, that's exactly it
Is there some version of RaycastHit2D that will return every object it hits instead of just the first one?
if I were to call a version of the method in a previous inheritance instead of the very first, how would I change that to do so?
I'm having issues with it immediately hitting the background currently, but I also want to be able to see all of a pile of objects, then pick the lowest
IIRC, it does not empty (null out) the array but overwrites it when called. make sure to manually clear the array . . .
not a RaycastHit2D but there are different raycast methods that can return more than one RaycastHit2D
RaycastHit2D is just a struct containing information about an object detected from a raycast. you want to look for a method that returns a collection of them instead . . .
Is there some way I can search the Unity Scripting API site (or google, therefore) to be able to figure out what different methods return them?
base.Method calls its immediate parent class's method, not specifically the one on the parent highest in the inheritance hierarchy
!api
💻 Learn in detail about the scripting API that Unity provides https://docs.unity3d.com/ScriptReference/
Yes, I'm there all the time
then look at the Physics2D class
oooo I see, thank you boxfren
I second the thanking
this is rather strange, but I am replacing text components in an object with text mesh pro,
but it will work fine for all the text components except the last one.
The last component with remove the default text component, but wont add the tmp counter part, even tho the code (when debugged) shows the added component is not null
static void ConvertTextToTextMeshPro(GameObject target)
{
if (removeEffectComponents)
{
var sha = target.GetComponents<Shadow>();
foreach (var cmp in sha) Undo.DestroyObjectImmediate(cmp);
var outl = target.GetComponents<Outline>();
foreach (var cmp in outl) Undo.DestroyObjectImmediate(cmp);
}
Text uiText = target.GetComponent<Text>();
if (uiText == null) return;
TextMeshProSettings settings = GetTextMeshProSettings(uiText);
Undo.RecordObject(target, "Text To TextMeshPro");
Undo.DestroyObjectImmediate(uiText);
TextMeshProUGUI tmp = target.AddComponent<TextMeshProUGUI>();
tmp.enabled = settings.Enabled;
tmp.font = settings.TMPFont;
tmp.fontStyle = settings.FontStyle;
tmp.fontSize = settings.FontSize;
tmp.fontSizeMin = settings.FontSizeMin;
tmp.fontSizeMax = settings.FontSizeMax;
tmp.lineSpacing = settings.LineSpacing;
tmp.richText = settings.EnableRichText;
tmp.enableAutoSizing = settings.EnableAutoSizing;
tmp.alignment = settings.TextAlignmentOptions;
tmp.enableWordWrapping = settings.WrappingEnabled;
tmp.overflowMode = settings.TextOverflowModes;
tmp.text = settings.Text;
tmp.color = settings.Color;
tmp.raycastTarget = settings.RayCastTarget;
Debug.Log(target.name + " converted to TextMeshProUGUI");
}
it says text_1 convert but text 1 is clearly not shown
the component is missing...
Place a break point on the log statement and see if the component was added successfully. Maybe you've got something else removing it.
Ive done this already, but will do again!
So this implies that visually in the scene, the object has a text mesh pro component attached. Can you verify this?
At the text_1 break point
visually, there exist no component, even tho the code says its there
At the break point?
So the component was created in scene and visible at the break point
Are you dealing with prefab here?
yes
Probably need to do something like SetDirty
Either that or there's another script removing the component
Else cathei is likely correct
You can use SetDirty when you want to modify an object without creating an undo entry, but still ensure the change is registered and not lost.
Your last change isn’t making Undo entry so
so, that prefab has 4 text components, the first 3 get changed just fine, its the last 1 that doesnt get added...
After adding a component, there are no undos ever introduced - with the exception of the function being called again.
Ummm, why did you make Undo call the get add component statement 
//stuff
Undo...
//stuff
SetDirty...```
since you're wanting to modify the object thereafter without creating an undo entry
yea,
idk why its doing this
it removes the text, but it doesnt addthe component
didnt refresh the prefab in video
You can use SetDirty when you want to modify an object without creating an undo entry, but still ensure the change is registered and not lost. If the object is part of a Scene, the Scene is marked dirty. If the object may be part of a Prefab instance, you additionally need to call PrefabUtility.RecordPrefabInstancePropertyModifications to ensure a Prefab override is created.
Or record the object again at the very end as that automatically calls set dirty as well.
ok
If you do want to support undo, you should not call SetDirty but rather use Undo.RecordObject prior to making changes to an object, since this will both mark the object as dirty (or the object's Scene if it is part of a Scene) and provide an undo entry in the editor. You should still also call PrefabUtility.RecordPrefabInstancePropertyModifications if the object may be part of a Prefab instance.
I straight up dont even care about the undo
I just want it to work
nope diodnt work
The options for forcing Unity to Update the contents of the Editor: https://support.unity.com/hc/en-us/articles/115002294603-How-do-I-make-a-scene-dirty-when-modifying-a-property-via-script-
Symptoms:
I modify a property via the scripting API.
The scene is not made dirty.
Cause:
Scripting APIs do not use the undo mechanism nor mark the scene dirty by default. One can, however, ...
I can't help you anymore than this. Make sure you read the entire contents of the message #archived-code-general message
thanks for the help
is there any way in Unity's physics engine to make one gameObject have a tugging effect on another?
for example, say I freeze a gameObjects position but not rotation, then attach another object to it and give it a velocity in the direction of Transform.right, I want that moving object to spin the stationary one while being restrained from moving away from it
Sounds like a job for joints perhaps?
Sounds exactly like you just need a joint
hey im trying to install Relay and Multiplayer Samples Utilities but both of these packages scream errors at me???
This is the main one:
"The type or namespace name 'Internal' does not exist in the namespace 'Unity.Services.Core'"
Why is this? Do I have to upgrade? I'm using 2020.3.29f1 LTS
CS0234
Share the details of the error. What file throws it? What's the stack trace?
reopening editor rn
If you downloaded the boss room samples I think that was built with 2022. Not sure if its required to be on a certain version but the NGO discord might have more specifics, it has a channel for each service like relay and the samples
nah didnt install any samples, just installed the package Relay from unity registry to get the error
where can I find the NGO discord btw?
Pinned in #archived-networking
The docs might even mention if you need a certain version
found the discord, ty
ill check the docs now
2020.3 seems fine?
....i deleted the library folder and reopened the editor and it works now
Thanks Unity!
how often can I, like, call a function that deletes 100 gameobjects, before it gets out of hand?
Depends on your hardware, the deleted gameObjects and your definition of "out of hand".
the average hardware, each gameobject is only a spriterenderer, collider2d, and special information script at most, and out of hand is like, the same way it would get bad if a gameobject was being created and destroyed every frame I guess? though I actually have no idea what that causes other than garbage collector, and possibly lag
Well, it's hard to give you any specific number. Try it and use the profiler to get precise metrics.
i guess i'll have to just see what happens when I start doing that with my project
i'm allowed to destroy an object from within that object right?
or does everything collapse? i doubt it though, since it sounds convenient
Yes. Though do note that any running code would keep on running until it returns.
I can only slide one enemy in platform when both are walking on the platform
can anybody help me to sort this out ?
literally you try to access a destroyed gameObject
assume your have 90 fps, then in one second this gameObject will move to backward by 90*0.02*5=9m
it needs 1111 seconds to destroy this gameObject (if this gameObject is start from z=0), i usually not turn on play mode more than 10 mins so idk
it gets destroyed in a second
idk where your gameObject start at, check the initial position and idk why you use fixed dt in update
First step is to actually look at the full error message and see where it's happening
The object is at 0, 0, 0
And I have to use delta time so that, the speed increases depends on time(seconds). if it is not there, it speed increases wrt fps. which changes with each computer
@leaden ice this is the full error msg
fixed dt is not delta time, it is used in fixed update loop, in update loop we usually use delta time
btw i forgot will this error redirect you to the script, is this error directs you to this line or other line?
groundtile has to be a prefab. You've dragged in an object from the scene.
I think the groundtile has the ground script on it and it will destroy itself causing this script instantiate a destroyed go
groundtile is a variable name which i used to assign a prefab
Anyways that doesn't matter.
The problem here is how Destroy executes itself without passing the condition
I have not it used in any other scripts
the gameobject is at 0
put Debug.Log($"{name} was destroyed because its z position {transform.position.z} is below kill limit {kill}") inside the if statement
The speed is public variable and something may accidentally change it
The log clearly says what's happening
The scene and hierarchy doesn't look like that
Look like what
clones are not being destroyed
Where did you put that log statement
wait a sec, can u clarify, which one is the log
So yeah of course it's not destroying you deleted it
oh, I thought I had to replace
Added it again
And once again I'm back to where I started
That's good.
Now then, stop accessing the object after it's been destroyed.
Again, 99% sure this is the problem: #archived-code-general message
there's no way you get that error if you actually dragged in a prefab there
and you can see a non-prefab "Ground" object without the "(clone)" specifier in the scene in the screenshot
$20 says they don't know what a prefab is
Yep you've dragged a scene object in
Basically the reference groundtile is a object in scene that has been destroyed. You cannot Instantiate/clone it anymore. Maybe reference a prefab instead of a scene object that will be destroyed.
If it's a blue object in the scene hierarchy that's not a prefab, it's an instance of a prefab. Delete it from the scene and drag the actual prefab into the slot in the inspector
Else don't destroy the original object - preferrably use a prefab though.
I have used 'groundtile' as a gameobject only to spawn the prefab 'ground' and I have used 'groundtile' only once in the script.
I'm being overwhelmed 🤯
Your vocabulary is a bit odd. Prefab would be resources in your asset folder or project that aren't in the scene.
What they are asking you to do is to reference the prefab (should not be a scene object) and clone that.
is dragging from hierarchy is not same as dragging from asset?
This has to be a prefab. But you can see from the icon that it's not, you've dragged in the object from the scene which is not a prefab
It is not.
When the object in the hierarchy is destroyed, it'll no longer exist and throw the errors you have been getting.
easy money
Prefab manual: https://docs.unity3d.com/Manual/InstantiatingPrefabs.html (a lot to read though...)
Hi! Does anyone know how should I deal with that?
Assets\ShadowCasterRendererSilhouette.cs(10,9): warning CS0618: 'ShadowCaster2D.useRendererSilhouette' is obsolete: 'useRendererSilhoutte is deprecated. Use rendererSilhoutte instead'
In Unity 2023.1.8f1 ShadowCaster2D component, there is no longer useRendererSilhouette field, but Casting Options enum, from which none is like "useRendererSilhoutte "
Start by checking for updates in your package manager for the lighting package
If you're on a newer version of Unity, there should be available updates to packages as well
(This is assuming you upgraded your Unity midproject)
I'm guessing everythings working now
Wondering if anyone can help me. The player is the small object with the camera icon. I have this script that should trigger when it collides with the torus but it seems to trigger constantly. Any idea what is going funky?
private void OnTriggerEnter(Collider other)
{
if (other.tag == "NPC")
{
currentNPC = other.gameObject;
Debug.Log("can ask");
}
if (other.tag == "Player")
{
Debug.Log("Player is here!!");
evil.SetState(EvilGuy.State.FollowPlayer);
}
}
What's a torus? Show the logs?
Also, although it will not make any difference gameplay wise consider using the CompareTag method rather than tag with string comparison
Check the collider for the shape. Don't recall concave shapes working nicely in Unity.
Oh ok
How are you able to check the shape of a mesh collider? I can't seem to view it
Nevermind I'm stupid lol
It seems to wrap around the mesh just fine though not sure if maybe it's including its middle which is stuffing it up? Would there be a better way to check for a collission with the perimeter?
Can't it just be a sphere collider? Doesn't look like the middle part is accessible anyway
Why not print the name of the thing you're colliding with?
a torus is the shape of a donut
you can check specific collisions with CompareTag (instead of tag ==). It’s just safer.
I also agree with praetor, that you should Debug.Log(collision.gameObject.name) to troubleshoot better
i sometimes find really strange objects triggering things that they really shouldn’t, because a tag/layer got changed at some point
So I'm trying to simulate the trajectory equation and I'm not sure whether the equation itself has something wrong with it or maybe because of some event weirdness, I'll show what happens in Unity and the code:
This is the function itself:
{
float y = -(gravityValue/(2 * velocity * velocity * Mathf.Cos(angle) * Mathf.Cos(angle))) * x * x + Mathf.Tan(angle) * x;
return y;
}
And it works for parabolas and other things
I'm getting the velocity and angle using these:
Angle: float angle = Vector2.Angle(direction, Vector2.right);
Initial speed:
float magnitude = (arrowShower.lineRenderer.GetPosition(1) - arrowShower.lineRenderer.GetPosition(0)).magnitude;
I'm gonna continue debugging this, just wondering if somebody might have a clue why it won't be working
Mathf trigonometric functions operate on radians, you're passing in degrees
Thank you! I knew it was simple solutions like these that just escape me
How can I execute a callback in a VisualElement when it's repainted/redraw?
are you looking for the OnGUI callback? https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnGUI.html
Not exactly, I want to take a VisualElement, do root.MarkDirtyRepaint(). And then all its hierarchy receive the event that they will be repainted.
is there a way to strip text of tags in TMP, similar to GetParsedText() but without having to assign it to TMP text first and updating mesh
some utility method
or better yet - is it possible to replace TMP rich text parser with my own so I can control what tags I want to allow and how to escape stuff?
I figured kind of working solution where I just replace < with <noparse><</noparse> and that prevents normal TMP tags from working and convert my own tags into TMP tags but I'd like to know if there is a better solution for this
unfortunately I don't have any experience with UITK so I can't say. Did you ask in #🧰┃ui-toolkit ?
Oh, I forgot about the existence of that chat. Thanks
also is there a way to intercept / consume input before it goes into TMP input field? with either new or old input systems
for example if I want to handle some key combination somewhere even if input field is focused and prevent input field from receiving this input
you don't necessarily need to MarkDirtyRepaint in UITK unless something changed with the geometry and you need to immediately update those changes, for example, changing font-type of a TextElement. Most of these stuff handled internally by default for all uitk controls except TextElement
Do you have the right using at the top?
I think it's using UnityEngine.UI but I'm not sure
Is you VS configured?
how exactly configure VS?
!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.
It might be, but I can't see any other code to confirm. Also see I edited my first message for the namespace I think Image is in
IDE is configured properly so that isn't the issue
That is base configuration. Not necessarily Unity configuration
I'm using system.drawing for what I need, not the UnityEngine.UI
Ah ok. Dunno then
😭
The error clearly states that you have a missing assembly reference. You will need to refernece System.Drawing in your assembly definition.
That isn't an assembly definition
And I'm so dumb for missing that sorry
Only looked at the first error
where can I find it then?
Here's unity's page on Assembly Definitions
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
pretty sure you cannot use system.drawing in a Unity project anyway
iirc it's tied to WinForms
so that means that I'll also have to get WinForms stuff running inside of Unity
the hacky wacky workaround is to find the DLL and include it in your project
what are you actually trying to do though
why do you need this
but the dll has dependencies which wont work in Unity
this is all a big XY problem
trying to use stuff from System.Drawing in order to use a external DLL that contains code I need
Why though?
what are you trying to do
That's they x, they want the y
to use a external DLL that contains code I need
oh no VS2019 crashed
how on earth do those two ideas have anything to do with each other?
this is why you're getting interrogated about an XY problem. It makes no sense.
probably because the external dll relies on a class defined in system.drawing
did you mean to say you're trying to load an external DLL so that System.Drawing works? that would at least make more sense.
I'll explain the problem:
I'm using a library/DLL that contains code. The code is to load a more obscure image format.
The library/DLL relies on System.Drawing for the image extraction logic, yet Unity Engine doesn't like that library it seems
don't be afraid to give details, we are all grownups here
What format are you trying to load, and why do you need to load that particular format?
And why this particular library/DLL? Maybe there's another library without any external dependencies that does the thing.
if y'all really want to know so badly: a Texture Palette Library (or TPL for short)
if you want help we need to know, so dont be snarky
yeah I'm sorry about earlier
alright so I'm using libWiiSharp to load the TPL, but that relies on System.Drawing for some logic/code
but uhh, gotta be honest: never heard about the XY problem before. Interesting to learn about
ok, so you're looking to make use of this code in particular https://github.com/TheShadowEevee/libWiiSharp/blob/master/TPL.cs
correct
and this is a pretty esoteric format, I'm guessing
So this is for modding?
The format ois actually well described here as far as I can tell https://wiki.tockdom.com/wiki/TPL_(File_Format)#File_Header
Looks to be specific to the Wii
https://hmapl.wordpress.com/2019/10/06/calculating-xxhash64-values-from-tpl-texture-files/
this may help, no library needed
But I'm looking at https://github.com/TheShadowEevee/libWiiSharp/blob/master/TPL.cs and I'm not seeing what actually is using System.Drawing in here. Maybe it would be easy to fork and port to the Unity types.
easy peasy, change Image for Texture2D and job done
I'm not sure if it will be that easy, but I think it might be the only option I have
of course it's easy they are both Image formatters with nearly identical API's
oh that's great
that's what I was figuring, yeah
time to get coding replacing
should be a straightforward fork/port
though, I'd like to ask, isn't it maybe easier to then just download the code and add that into Unity and edit, instead of forking whole project?
nvm it's GPL-3 I have to fork it
I'm using "fork" colloquially, either of those would work
fork the project outside of Unity then just copy the bits you need to your project
Just make sure you follow any GPL-3 licensing requirements 😉
I would just clone it if I'm making mods which wont be pushed
I need a lawyer to sum it up, it's LONG that license
oh yeah that also seems like a fair idea
but yes, in general a lawyer is a good idea 😆
https://www.gnu.org/licenses/gpl-faq.html#ModifiedJustBinary that's what I'm looking for
no problem, just put your modified version on your own public git repo
I don't need to also provide a local copy of the source along with the modified binary?
no, just a link to the git repo in the docs
normally I have a separate attribution UI where I list all of the used code/assets and the source repos/web sites
no one ever looks at it, but it fulfills your obligations under the licenses
"forking" a repository would have no bearing on its GPLv3 license. If you integrated GPL'd code into your own program, you would need to license your work under a compatible license as well (probably also the GPLV3)
If you could keep the GPL'd code at "arm's length" from your own code, then you could get away with keeping the rest of your code proprietary
would you mind to elaborate on "arm's length"?
The FAQ talks about it, but it means that the code is clearly separated into multiple programs
note that I don't work with copyleft licenses much so I'm only a little more familiar than you are
How do I get the position of this enemy to be based on the world space,and not the camera space? I'm not understanding what I need to do in the script. You can see the xPos is -1.3 which I do not want
` for (int i = 0; i < enemyNames.Count; i++) {
string enemyName = enemyNames[i];
GameObject newAnimator = Instantiate(animatorPrefab, new Vector3(0, 0, 0), Quaternion.identity);
newAnimator.transform.SetParent(this.transform, false);
BattleEnemyContainer battleEnemyContainer = newAnimator.GetComponentInChildren<BattleEnemyContainer>();
BattleEnemy battleEnemy = Resources.Load<BattleEnemy>("BattleEnemies/" + enemyName);
battleEnemyContainer.battleEnemy = battleEnemy;
if (enemyNames.Count > 1) {
float alignResult = i / (enemyNames.Count - 1.0f);
float newXPos = Mathf.Lerp(-battleEnemy.xOffset/2 * (enemyNames.Count-1), battleEnemy.xOffset/2 * (enemyNames.Count-1), alignResult);
Vector3 newPos = new Vector3(newXPos, battleEnemyContainer.transform.localPosition.y, battleEnemyContainer.transform.localPosition.z);
battleEnemyContainer.transform.localPosition = newPos;
}
battleEnemies.Add(battleEnemyContainer);
}`
Im not using worldToScreen space at all, so I don't get why
The x position in that image is the offset from its parent, not camera position. Afaik, there is no way to show it differently. It DOES have a worldposition, which you can view using a debug simply with transform.position
Oh, recttransform
One sec
mmmm no? see look if I move the enemy to the left
it's position is -4? that's not based on the same reference anymore, isn't that camera space or something?
its not just localPosition is what I'm saying
yeah then I still have to go with the DLL solution.
ig I could set build output location to the Assets folder then
Yeah sorry, I didn't look close enough. RectTransform is offset from its ANCHOR point. So still basically local.
These are UI elements, right?
not your fault, it's hard to tell with limited pictures
yea they're in a Canvas
but other objects in the Canvas behave the way I'd expect
its just these ones with the weird position
the reason this is frustrating is that i'd like to have the same animator for the Player and Enemies, but I can't do that if their positions are on some different scale
Why not just make those enemies be in world space?
what about taking them off the canvas and rendering them with an overlay camera?
Hey, does anyone know how can I run callbacks from a custom event system on Unity's main thread?
Currently I am using this as a solution - https://github.com/PimDeWitte/UnityMainThreadDispatcher.
Is there a better way?
I'd like to get them in world space, It seems like maybe the procedural generation is what's causing the wrong positional reference?
ideally without adding in new cameras
why are they on a canvas?
im assuming it's because it's a battle scenario?
because they behavae with the mouse, yeah its a battle
not sure if it was the best setup
but it works shrug
I really believe rendering them with an overlay camera would be best. You could try changing their rect transform to a regular transform if it lets yo, but that would probably be actually terrible to do.
why don't you want to add more cameras?
This code:
https://hastebin.com/share/gilesewago.csharp
Is getting these errors:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Well, I'm just not understanding why the rect transform has anything to do with it. The parent is on a rect transform and it's using the world positional space
perhaps all the gameobjects in the hierarchy under the canvas do not have rect transforms
I'm not against the other camera per se, I just don't think it's actually fixing the problem
as far as I know the correct way to use it is to edit the rect tranform values, not the world position.
if you check character space does it have a rect transform?
yes it has a rect transform
Check to see if soulText is null. The other errors are editor errors. Try restarting
and the Player object uses a regular transform, but it's animator uses a rect transform
(player animator is child of the Character space)
sorry, idk then. Maybe that's your reason. I believe all transforms under UI are suppose to have rect transforms.
yea i mean, that makes sense. technically the canvas is supposed to be in screen space anyway right?
I had copied the player object over from a different scene where it wasn't part of the UI
so that may be why its behaving differently...
so maybe i just change the player to use a rect transform
soultext is not null
that should standardize everything to the screen space
soultext references a textmeshpro object
Show the inspector at runtime
Because the error says it is null. soul can't be null
changed Player to use rect transform, it's still in world space wtf
up top says the error is on line 32
Line 32 in the link you sent is:
soulText.SetText(Mathf.CeilToInt(soul).ToString())
correct
that's where it says the error is
it says object reference not set to instance of object
You cropped the image, is this at runtime?
yes
:(
also, seperate issue, lerping soul obviously causes deceleration, but lerping basesoul only decreases the value of soul one time
This means the object you're trying to reference is null. soul can't be null and the only other reference there is soulText. So I have no idea.
why is the namespace not recognized? What's the correct namespace to use?
Why obviously? Lerp only gets a value between two other values. It doesn't implicitly decelerate unless you implement that
This causes deceleration:
soul = Mathf.Lerp(soul, 0f, (drainPerSecond / 60) * Time.fixedDeltaTime);
This causes it to only decrease once:
soul = Mathf.Lerp(baseSoul, 0f, (drainPerSecond / 60) * Time.fixedDeltaTime);
what's the command to teach people how to use lerp? !lerp no i forgot?
ik how to use lerp
i've used it before
that's not how you use lerp correctly
ok, then how would i use it correctly to make soul linearly decrease by drainpersecond
I figured it out, it was the scale of the BattleEnemyManger was off. So it wasn't screen space at all... it was just shrunken positions that appeared to be screen space LOL
!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.
hello, I' mtrying to make a basic collision avoidance script ,and I run into the problem of it not working
here is the code for it
velocity = (new Vector3(targetPoint.position.x, targetPoint.position.y, 0) - new Vector3(transform.position.x, transform.position.y, 0)).normalized * walkSpeed * deltaTime;
transform.up = Vector3.Slerp(transform.up, (new Vector3(targetPoint.position.x, targetPoint.position.y, 0) - new Vector3(transform.position.x, transform.position.y, 0)).normalized, deltaTime * turnSpeed);
weight = 0;
Vector3 moveForce = Vector3.zero;
for (int i = 0; i < rayCast.Length; i++)
{
Ray2D ray = new Ray2D(transform.position, rayCast[i].up);
RaycastHit2D hit;
if(hit = Physics2D.Raycast(transform.position, rayCast[i].up, .7f, collison))
{
moveForce += -rayCast[i].up * hit.distance / .4f;
inverse = 0;
}
}
moveForce /= rayCast.Length;
Debug.DrawRay(transform.position, moveForce, Color.red, Time.deltaTime);
moveForce = transform.InverseTransformPoint(moveForce).normalized;
Debug.DrawRay(transform.position, moveForce, Color.green, Time.deltaTime);
moveForce = Vector3.Project(moveForce, transform.right);
Debug.DrawRay(transform.position, moveForce, Color.yellow, Time.deltaTime);
velocity += velocity.magnitude * moveForce.normalized;
transform.GetComponent<Rigidbody2D>().MovePosition(velocity + transform.position);
you're multiplying the interpolation value by Time.fixedDeltaTime. Instead you would want to just pass in drainPerSecond, which should have Time.fixedDeltaTime added to it divided by 60, like this:
drainPerSecond = Mathf.Clamp01(drainPerSecond + Time.fixedDeltaTime / 60);
Mathf.Lerp(baseSoul, 0f, drainPerSecond);
why are you changing the value of drainpersecond?
drainpersecond should never change
for some reason it works when the object is it's on left side, but not on the right side, it goes to the left only.
The raycasts are transforms placed in a circle around the agent
I have no idea at this point
for Lerp you are suppose to increase or decrease the 3rd parameter between 0 and 1.
why?
perhaps you are looking for Mathf.SmoothDamp?
https://docs.unity3d.com/ScriptReference/Mathf.SmoothDamp.html
because that's how lerp is used. It interpolates between two values, x and y, by t. When t = 0 result is x, t = 1 its y. t = 0.5 its half way between x and y.
so for this you would want to multiply Time.fxedDeltaTime by the speed. So perhaps like this:
drainTime = Mathf.Clamp01(drainTime + Time.fixedDeltaTime * drainPerSecond / 60);
Mathf.Lerp(baseSoul, 0f, drainTime);
this sounds more like a place for MoveTowards...
not really. They're using Mathf.Lerp, not Vector2.Lerp
current = Mathf.MoveTowards(current, 0, Time.deltaTime * drainRate)
Mathf has a MoveTowards (:
Saves you from having to clamp it from above or below
Works perfectly thank you
yea fen's solution is better. No idea mathf had that function.
I wish it had a Distance method
it's just Mathf.Abs(a-b) of course
but it'd be consistent
this :(
does it fail to compile in the editor?
are you using asmdefs?
idk what that is, so no?
asmdefs let you break your code into several assemblies
oh, assembly definitions. No, i'm not
Assemblies have to explicitly reference other assemblies they want tou se
That would cause this problem
hmm
some assets do come with their own asmdefs btw
TMP for example
I believe it would say that here, right? It only says to include the using statement.
https://docs.unity3d.com/Packages/com.unity.test-framework.performance@3.0/manual/taking-measurements.html
because it's normalized. a value of 0 will return a: 1st param, a value of 1 will return b: 2nd param with anything in-between a blend of both a and b . . .
This would be a problem with your code, not the package
nanhh asmdefs would matter if the scripts is in the same folder as asmdefs file
it's just in the assets folder (unorganized, ik, i'll get to it later)
maybe you can try regen project files
ohh
You can double check there isn't an asmdef affecting you here by searching your project for t:AssemblyDefinitionAsset
🤔 just popped up
but if you don't see one in the root, then that probably isn't it
I don't understand what prompts that error.
I know what it means, but I also don't see why entry-points would be relevant
"failed to resolve assembly" It's the editor assembly, but perhaps this package is incompatable with my unity version? it says 2020.3+, I'm in 2022.3
newest version is 2020.3
nah, the package clearly says it's compatible all the way up to 2023.2
true...
ah, I was going off of this, but I forgot that 3.0.2 wasn't showing its unity version
why is unity telling me this enum needs an accessor? lol
because Enum is a type.
You want to use enum not Enum
damn man. I didn't catch that when I installed it.
Ah right, thanks
Oh, I mean I was saying "nah, I'm wrong"
is there a different way to run benchmarking/performance tests? I was told to not just use the real time since startup - time since startup stored in a variable
I meant i didn't catch that i read 2022.3, which I'm in. Ig they changed something between 2022.1 and 2022.3 that broke it.
omg typos
after all, it doesn't list 2022.3, it jumps to 2023.1, so maybe something broke that they fixed right after??
only thing I can think of really
also this when I add through manifest following instructions in the docs:
AFAIK, most benchmarking in Unity tend to use the System.Diagnostics.Stopwatch class, unless your maybe looking for something else?
this package was recommended to me because I seem to be getting worse performance in my build than in the editor even with things like VSync disabled. For example i have a method that takes about 1.3-ish ms on average to execute in the editor in play mode, but in a build it takes about 8-ish ms.
It's a pathfinding method I've multithreaded so it doesn't actually hang the execution of the program when several units need to pathfind at once, but in the build sometimes there is a noticable delay between clicking and when units start to move, which is not the case when I'm testing in the editor. It's pretty early for optimization in my game, but I'd rather get the pathfinding running smoothly so I can be testing in a build smoothly.
Ok. Having more problems.
- The soul bar only starts decreasing after soul = 0, even with CheckDeath disabled, and sometimes it just doesn't decrease at all
- I get an "object reference not set to instance of object" error when i try to set the text value of soultext to soul.tostring()
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
link again
Ah I see, hmm, im not an expert on that level of optimization, I personally havnt messed with multi-threading much, though im guessing those ms numbers are from the Profiler hooked into a build?
those ms are from:
float startTime = Time.realtimeSinceStartup;
// do pathfinding stuff
Debug.Log($"{(Time.realtimeSinceStartup - startTime) * 1000:F2}");
I've also hooked the profiler into a build to check the timings of the methods running on the threads, which are worse as well, but I can't seem to get the timing of the entire operation with the profiler due to me using await Task.Run(() => //pathfinding method);
and I turned off vSync, although I'm not sure if it would be affecting this here.
it's just strange to me that the editor would have better timings since usually you hear that the build is faster than the editor.
Yeah, that is odd, unless maybe because its using a Task, that Unity doesnt calculate it correctly or "skips" some of its logic or changes it in some way while in the Editor? Im not sure if itll help, but if your pathfinding method is able to set a DateTime variable, maybe after its completed, you could compare DateTime.Now - startDate to get a TimeSpan, which should also give ms
what is the difference between using something like Physics2D.OverlapArea and using a cast like Physics2D.Boxcast? they both seem to cast shapes to detect collisions
do yk how to read ms with a trailing decimal from a TimeSpan? I can only seem to get the Milliseconds as an integer, so it just rounds it i guess.
Oh, i got it. Yea, the previous method had correct timings.
A boxcast fires a box in a direction
overlap area checks a certain area for any colliders overlapping with said area, box cast fires a box in a direction like a raycast
thank you both :) that makes perfect sense
yk what, I wonder if it was my mistake. In a build the debug.log probably opens the file (or takes longer to send information to the console when connected to the editor) then writes, which adds more time to the operation before it logs the current time - the start time. I'll test rn.
You can think as a boxcast as a thick raycast
it does seem to be mostly my mistake. The times in the build are slightly worse than in the editor, but that's tollerable since it won't hang the main thread from lots of pathfinding operations.
Interesting, guess it was kind of a red herring with Debug.Log, though in a way its good you found it was a simple fix and not something more complicated
I am new here. is this the chat to clear doubts?
If code, maybe if not code, no.
does not fit as scripts.
Not idea what you mean, but try #💻┃unity-talk
all I had to do was save the prefab lol
PrefabUtility.SavePrefabAsset(gameObject);
still struggling here
I need another pair of eyes here. I'm not sure what's wrong with this code that should be moving an object to the edge of the screen if it's off screen. The X position works flawlessly. Y positioning does not. As soon as it's off screen it snaps to a specific point in the world way off from the edge of the screen.
https://gdl.space/danotenide.cs
Context: activeCamera is an orthographic camera that is viewing the world from above. MaxViewportRect is a Rect set from the inspector, currently 0.15f, 0.15f, 0.7f, 0.7f. I'm guessing I've got something wrong with my math or a flipped sign or something but I just can't see it.
what's with the + 1 on line 10?
also, targetXPos is starting out as a world-space coordinate
what kind of object is this
oh nvm, I misread that. that's not happening.
UI or world space?
I thought it was getting a viewpoint position assigned to it
World space SpriteRenderer
It's an icon to indicate a location, so it's offset by 1 vertically so it's pointing at the location without actually covering it
ah, ok
oh, you're using y, not z, in lines 20 and 25
don't you want z?
it's a world-space coordinate
ooh yeah that sounds right
Ah, right, the world point would be Z-forward.
i love dealing with XZ coordinates
Lemme try it
i kept screwing that up in a game jam
Bingo bongo, that solved it. Thanks!
I actually wrote extension methods that would turn a Vector3 into an [x,z] Vector2
and a Vector2 into a [x, 0, y] Vector3
i still did it wrong constantly
(:
It might be easier to avoid the problem if you worked entirely in viewport space until the end
less clutter
I feel that
I was using XZ coordinates to look up map-gen data
Hey,
My raycast commands keep returning null although the gameObject is point at target
target is 5500 units away.
maxRange is 35,000 units
Here's the snippet where the command is created.
Vector3 origin = lGameObject.position;
Vector3 direction = lTarget.position - lGameObject.position;;
QueryParameters queryParameters = QueryParameters.Default;
queryParameters.layerMask = layerMask;
RaycastCommand raycastCommand = new RaycastCommand(
origin,
direction.normalized,
distance: maxRange,
queryParameters: queryParameters
);
It seems as if it's random when the result is not null it may take multiple jobs before a hit is returned
the obvious question is what is the value of your layermask?
1|3|8|10
Targets are 8
how did you build the layermask
not good
It's an argument in the MonoBehaviour
that comes from where?
Layer mask of layers 1 & 3 & 8 and 10 is
1<<1 + 1<<3 + 1<< 8 + 1<<10
yeah if you literally wrote 1 | 3 | 8 | 10 somewhere that's not correct
The values are selected from the enum
I don't care where they come from, you are using them incorrectly
Ok you're dragging this out like pulling teeth. Are you saying you have:
public LayerMask layerMask;``` and you set it up in the inspector?
If so, that's fine
yes
can you shoew the code where you actually run the command?
handle = RaycastCommand.ScheduleBatch(commands, results, raycasts.Count, raycasts.Count + 1, default(JobHandle));
is maxHits larger than results?
can you just show the full code?
private void Update()
{
if (batchingState == BatchingState.Ready)
{
CreateRaycastBatch();
}
if (batchingState == BatchingState.Batching)
{
if (handle.IsCompleted)
{
handle.Complete();
batchingState = BatchingState.Collect;
}
}
if (batchingState == RadarSystemBatchingState.Collect) ReadRaycastBatch();
}
private void CreateRaycastBatch()
{
Debug.Log("CreateRaycastBatch");
List<IntermediateRaycastInfo> raycasts = GetRadarRaycastInfo();
batchingState = BatchingState.Batching;
results = new NativeArray<RaycastHit>(raycasts .Count, Allocator.TempJob);
commands = new NativeArray<RaycastCommand>(raycasts .Count, Allocator.TempJob);
int i = 0;
foreach (var raycast in raycasts)
{
QueryParameters queryParameters = QueryParameters.Default;
queryParameters.layerMask = layerMask;
RaycastCommand raycastCommand = new RaycastCommand(
raycast.origin,
raycast.direction.normalized,
distance: maxRange,
queryParameters: queryParameters
);
Debug.DrawLine(
raycast.origin,
raycast.origin + (raycast.direction.normalized * maxRange),
Color.cyan, 1
);
commands[i] = raycastCommand;
i++;
}
handle = RaycastCommand.ScheduleBatch(commands, results, raycasts.Count, raycasts.Count + 1, default(JobHandle));
}
ok so what does ReadRaycastBatch do?
yeah wait a sec sorry if the code is messy its hard to paste
!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.
private void ReadRaycastBatch()
{
Debug.Log("ReadRaycastBatch");
batchingState = BatchingState.Ready;
int i = 0;
foreach (var hit in results)
{
if (hit.collider == null)
{
i++;
continue;
}
i++;
Debug.Log($"hit={hit.collider.gameObject.name}")
}
results.Dispose();
commands.Dispose();
}
so what's the issue here? You're seeing hit=null or something?
yes so the hit is null either tho the gameObject is facing the target and debugging the ray with Debug.DrawLine shows that its aligned
The batching process takes multiple frames would that cause trouble with colliders?
Not a jobs professional here but
if (handle.IsCompleted)
{
handle.Complete();
batchingState = BatchingState.Collect;
}
Isn't the condition backwards here? I suspect you never run the commands
I had trouble with it claiming that the handle is not complete even if handle.IsCompleted is true
So I think that method waits for the jobs to be complete.
Docs say:
"ensures that the job has completed"
Yeah it seems like it's blocking execution until it's done
Can you do that without all the conditions you have, for debugging purposes?
Issue commands, complete the handle, read results all at once
yeah, just try handle.Complete() and check . . .
Still no and had horrible lag spikes
Yeah lag spikes are normal because the method freezes the game until the handle completes
At least now we know it's not about the code structure and how it's "waiting" for the command to complete
It might be floating point error because I'm 100,000 units out
Lets try with floating point origin shifting
It's not 🤔
Its weird how it lags because I only have 2 raycasts at the moment
I imagine the raycasts aren't the most expensive operation in this whole thing, spooling up a job might be
It only lags when results is being iterated
And not all the time
Only when a hit has happened
Excuse me, I'm having an issue about the Item Switch. I have 2 scenes: Overworld and Sword Cave.
1st: Whenever I start the game in Overworld, the bombActive is true, but wont show the desired sprite, until I press L Shift which activates Boomerang and shows said Item. And when Boomerang is on and press L Shift again it activates bomb and shows the sprite. Issue is that I want the bomb item sprite to show up at the beginning.
2nd: The code doesn't work at all whenever I go inside the Cave, nor when I start there. I press L Shift but neither item activates or show sprites.
If you can help me I will appreciate it a lot, thank you!
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.
On bomb active ur making it show the boomerage sprite and on boomerang actve ur making it show the bomb sprite
U just have to switch up the sprites
That is because when I press L Shift and it activates the switch item function it checks which one is active, if bomb is active, it will then activate the boomerang
I switched to the normal Physics.Raycast and it works now. Weird.
Oh because u dont have a way for it to check which one is active because theres no acess to switch item beseides when u press shift
U have the bomb set as true in start but it doesnt check if its true until u press shift
when stopping a coroutine, do I need to pass in the same value as when I started it?
Pass what StartCoroutine() returns. You'll need a variable
ah I see.
Also, I'm wondering...
is ~(1 << 6) (used as a layer mask) an operation that needs to happen every time (for example if I put this into a raycast), or is it turned into a constant by the compiler?
the compiler turns it into -65
https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTAbgIYBO6AHugLzoA/anHQAeUegBstANyMiAX2QKgA=
but even if it didn't, it's a simple operation that doesn't merit worrying about whether it happens multiple times
thx, just wondering
I'm using this code to spawn bullets in a Netcode for Gameobjects multiplayer fps
[ServerRpc]
private void ShootServerRpc()
{
GameObject new_bullet = Instantiate(bullet);
new_bullet.GetComponent<NetworkObject>().Spawn(true);
new_bullet.transform.position = transform.position;
new_bullet.SetActive(true);
}
and on the host's side it's fine
but when the client spawns a bullet, it spawns at the host's gun and then zooms over to the client's gun
i didn't even code bullet movement yet, so I suspect it's interpolating or something
any ideas why this might be happening?
bullet prefab has a network object and a network transform component
I tried doing that and it said "Operator '&' can not be applied to operands of type 'int' and 'bool'
Wrap parentheses around the first 2 terms (layer & goodLayer) != 0
I figured out a better way to make the trees not mess with the water, I use the minimum height, so the trees don's spawn at sea level
Hey I just have an important question about loading TextAssets. When I parse the textAsset.text variable into a JSON object it is extremely slow because it takes a long time to get all the data from the text. How can I load this in the background with a really efficient async or coroutine?
[SerializeField] private Transform geoTransform;
[SerializeField] private Transform frontiersTransform;
[SerializeField] private Material frontiersMaterial;
[SerializeField] private AssetReference geoReference;
private void Start()
{
geoReference.LoadAssetAsync<TextAsset>().Completed += asyncHandle =>
{
if(asyncHandle.Status == AsyncOperationStatus.Succeeded)
{
// This is really fast
TextAsset textAsset = asyncHandle.Result;
// This is not fast due to textAsset.text;
JObject jObject = JObject.Parse(textAsset.text);
foreach(JToken features in jObject["features"])
{
foreach(JToken coordinates in features["geometry"]["coordinates"])
{
DeserializeCountryFrontier(coordinates);
}
}
Addressables.Release(asyncHandle);
}
};
}
This object gets added by Unity to my scene, I dont know why. Any clues? It doesn't have any components aside from Transform.
I suppose it could be something to do with netcode for gameobjects (since looking it up that's the only related thing google can find, but I find it unlikely, however I haven't used netcode for gameobjects much). Do you have that installed? And how do you know it's added by unity?
The instantiatePrefab.transform.Rotate(Vector3.up, Random.Range(rotationRange.x, rotationRange.y), Space.Self); part of my code isn't doing anything, its supposed to rotate my prefab a random amount around the y axis. And it's not doing anything.
you are immediately overriding the rotation on line after that. I believe Quaternion.ToFromRotation is rotating the object to point along the hit normal, then you are essentially adding that rotation to the game object, then lerping between the rotation you applied on the 3rd line to that new rotation. What value is rotateTowardsNormal?
Never mind fixed my own problem
[SerializeField] private Transform geoTransform;
[SerializeField] private Transform frontiersTransform;
[SerializeField] private Material frontiersMaterial;
[SerializeField] private AssetReference geoReference;
[SerializeField] private GeoRoot geoRoot;
private void Start()
{
JsonSerializer serializer = new();
var path = Application.streamingAssetsPath + "/Data/Earth/Countries.json";
using FileStream s = File.Open(path, FileMode.Open);
using StreamReader sr = new(s);
using JsonReader reader = new JsonTextReader(sr);
while (reader.Read())
{
// deserialize only when there's "{" character in the stream
if (reader.TokenType == JsonToken.StartObject)
{
geoRoot = serializer.Deserialize<GeoRoot>(reader);
}
}
}
@dense estuary, updated my reply
Thank you, I fixed it by rotating it after lerping the rotation. rotate towards normal is a value between 0 and 1.
I needed to Rotate after setting the rotation. thats why it didnt work before
ok, just an order of execution bug. Also sounds like you're using the lerp right 👍
Wasn’t really sure what to ask but can someone give me some sauce for SFX playing programming patterns / common setups? (More specifically for menu related stuff that doesn’t care about positions and such
Right now I have a singleton with a singleton that just stores a shitton of audioclip references just so i can easily play stuff in a single line but curious how other people do it
But I do have one more problem. The trees are clumped up at some parts when i spawn them in. is there a way i can make them not do that. I spawn them using a raycast at a random coordinate within a radius. So could I somehow make raycasts not able to go too close to spawned in trees?
its like a raycast, but a sphere.
just check that it doesn't hit a tree. might want SphereCastAll: https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html
idk, I have Photon Fusion installed, but this didnt happen in the past
well if it was updated or perhaps some condition is being triggered to cause it to create that? Check to see if they have any kind of support form.
I can't use SphereCastAll because I can't use an ! on an array.
yea, you'd have to loop through what it finds and check every object to see if it's a tree.
@dense estuary A more sketchy approch could just be having a little collider above/around your tree prefab with a layer dedicated to just failing that raycast you do
that way your raycast hits the trees "aura" and fails because its too close
Question, is fine in FixedUpdate do rigidbody.AddForce(transform.up * val)? The rigidbody is updated in the physics step, but transform.up doesn't? Shouldn't be rigidbody.AddForce(rigidbody.rotation * Vector3.up * val)?
No, i mean i cant do this if its an array.
The transform is updated during the physics h
Update, so it should be identical to rb orientation at that point.
yea i know, you'd have to loop through the array and check if there is a tree, if not set some bool to true so it's like if(tree)
but if a single sphere cast works for you that's fine.
But if I modify rigidbody.rotation then it will no longer be valid transform.up, right?
I'm trying to implement a character selection screen with a circular carousel view (that is, if you keep scrolling left or right, you'll eventually reach the same character). I'm currently using a circular array to implement this since it felt like the most logical thing due to the problem. However, I'm having trouble when it comes to "repositioning" elements, so it acts like an eternal scroll.
Here's my code so far: https://pastebin.com/LA48CZTQ. Yes, I'm currently using DoTween to do the movement, but that shouldn't matter too much since it's just a prettier version of just repositioning things. I'm having brain trouble deciding if I should move the whole array left or right when scrolling and keep an index in the middle, or just move the index and calculate the boundaries in some other way (which is what I'm doing right now).
Hmm... probably not. Hard to tell. Test it and see for yourself.
You can also just apply force in local space.
That's guaranteed to work.
Ok, thanks
I'm referring to this one:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddRelativeForce.html
If you want to move the rb relative to it's orientation that would be the safest method.
how can i loop through the array?
wait, nvm
Maybe move the index and if it's < 0 or >= array.Length then set it to Length - 1 or 0 respectively?
Something like this? ```cs
RaycastHit[] hitCast = Physics.SphereCastAll(rayStart, minimumDistance, Vector3.down, Mathf.Infinity, layers);
for (int j = 0; j < hitCast.Length; j++)
{
}```
Yeah, definetly ! The array it's not the problem at all. That's a struct that I didn't include in the code, but it internally does basically that. I'm having trouble with like, the repositioning part of things. So let's say, since it should feel like an infinite scroll, once you reach index 0 it logically goes to index array.Length - 1 , but the visible part, where you just put the element of array.Length - 1 next to the element in index 0 on screen is what's making me squeze my brain juices haha
Well, I'm not sure what setup you have in the scene. Is the whole collection visible at the same time? Or just some of it? Can you share a screenshot/video of what it looks like?
It might also be helpful to explain the actual issue, as I don't understand it completely.
Yes I use this formulation
It's technically more correct I think
Yeah, I don't have any recording software in my pc but I can definetly share a screenshot or more detailed view of what's the problem
Why wouldn't you just use AddRelativeForce if you were doing that
for adding force I would
sometimes I want rigidbody.up for other reasons though
Is it okay if I send some screenshots here ? I don't wanna, like, flood the chat
It's just 3 tho , but still
yes you can send screenshots to help illustrate your problem
This is basically it
It logically works, however I can't for some reason figure out how to do the movement itself
Because when you point to the "last element" to be put as first, the "last" element it's always the same following an index
Yea, then if(hitCast[j].CompareTag(“tree”)) // stop loop, set bool to true or something like that, not sure how you have it set up.
I still don't entirely understand the issue, but if I get it right, you just need to update all the cards with the corresponding offseted data.
How many cards do you want to be visible on the screen at once?
Around 5, so the margin for the index to things to start moving it's +- 3
Right, but as I'm calculating stuff for some reason things get moved to positions that don't make sense or are just not what they should be
Let's say 5 cards are visible at once. And let's say the 3rd card is the one that's always selected.
Let's say you have them display data from 0-5 positions in the array. Once you scroll left, the card at position 0, would shift it's data index from 0 to -1, then fixed to the last position(let's say 31).
With the data from 31 fed into the card.
I have a gameManager object that has a public variable that tracks time, and i want at some point in time for a prefab to change sprite, but i can't drag and drop the gameManager object into the editor inside the prefab cuz some reason
so how would i access the time variable if i cannot check the game Manager?
Ok, so it sounds like a bug in the logic. Might want to debug it properly with debugger or logs.
Right now, there are 7 cards with 5 visible at all times in screen, the problem is that in my logic I'm calculating things in a "static" way instead of "relative", so, instead of saying, "hey, card 3, you have to move X spaces to the right" I say "following the i index iteration of a for loop, I can calculate where card 3 should be"
That leads me to the problem that the last card to the right in the case of scrolling to the left, gets put into where "it should be"
If the last card is already pointing at the last data position and you shift it to the next position, it should loop back to 0 obviously.
If you're not making that check, it would point at last pos + 1 causing an out of bounds error.
Yeah, it loops without a problem, when you say "pointing at the last data position" what do you mean ? I'm asking because there's no "data position" as it is, it's just a float value that decides where the card should go, the array doesn't store any information about it
Maybe I should ditch the idea of a "static" calculus, and make it more like a "move X float amount to the direction" and just make the last one loop
This doesn't go against the implementation of the circular array but it would mean to basically re-do everything I've done , lol
Okay, maybe I don't understand the issue after all. What float values are you referring to? What does it have to do with calculus and what do you mean by "static" calculus?
Is the issue with actually physical movement of the cards?
You'd typically have the UI independent of the data, so if you want a looping ui, it wouldn't matter to it if the data has reached the end of the data array or not. It would act and move the same regardless. If it doesn't, then your ui has a hard dependency on the data which is not correct.
Either make it a singleton, the field static or use one of the find methods to get a reference to your game manager at runtime.
For managing multiple UIs that can be shown/hidden, is there any reason to prefer hiding/showing a canvas over hiding/showing a panel or vice versa?
Organizational and performance concerns.
Having everything under 1 canvas might mean that all of the canvas elements are rebuild when you only want to modify one of them.
That being said, having them on separate canvases would increase draw calls, so ultimately it's "test and see for yourself" thing. If performance is not an issue, then you can go with any of the solutions.🤷♂️
Thanks for the insight!
I want to change every tile's sprite when a certain time passes, but the tile doesn't have a Sprite renderer?
https://hatebin.com/kamvhlpzzj <- Code
Yep. Tiles don't have sprite renderer.
Yes.
I suggest going through the tilemap section in the manual. It covers how to work with tiles at runtime:
https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles.html
i'll take a look into it later
It's kind of complicated to explain, but basically to "re-arrange" the cards I just loop from 0 to array.Length through the array and then calculate basing on the index and the difference of the i index currently looping and the index of the selected item. So the block of code that does that is this one:
int trackerPoint = index - i;
RepositionRectTransformToLocation(rect, trackerPoint * -distanceBetweenCards, trackerPoint * distanceBetweenCards);
That's just for the left part, but basically it goes from 0 to index and calculates like so:
i = 1, index = 3, distance = 100
trackerpoint = 3 - 1
RepositionRectTransformToLocation(rect, 2 * -100, 2 * 100);
And that method just sets the left and right parameters of one of the cards
private void RepositionRectTransformToLocation(RectTransform rect, float left, float right)
{
rect.SetLeft(left);
rect.SetRight(right);
}
Which, again, just sets the rect's left and right, I know you can't just acess those things with methods, but I coded some extensions that basically do that, that's why "SetLeft" and "SetRight" are correct.
Damn, hope I explained it a little better, lol
Hence why I call it "static", it just sets the card's positions without caring about where they were before. Just puts them in calculated positions
Even if it is UI, I'm just moving UI objects around, it's no different from moving gameobjects themselves
Wait, are you actually shuffling the cards around?
Changing their position physically?
Okay I see.
That's where you have the wrong approach imho. The cards should never change their physical position.
Card index 0 would always stay on the fat left side. The only thing that should change is the data that it displays.
O
I see
Right
So instead of just shuffling the things around
I should just update the information displayed ?
Yes.
But then how would you a transition of the cards ?
You know, showing how the left one moves right and so
I took the approach to actually moving them because I had in mind to use DoTween to move them and make it smooth, but it's some sophisticated way of just moving them
You'd have one extra card that doesn't fit on the screen on each side. You play an animation of scrolling all the cards to one side , then snap it back and reassign the data of each card.
You can still use dotween or whatever you want for your animation.
The point is that you only need to make it look like the cards physically shifted.
And why is it a bad idea to make them move ?
I'm just asking, is there any reason other than the fact that they're UI ?
It's inefficient, less performant and you'll get tangled in the logic of moving them around.
As it happened to me
I see
Well thanks about that, now it's just a matter of re-factoring things to implement that new approach
Does somebody know why my code doesn't work? The touch world pos is fixed on the cinemachine virtual camera pos instead of the touch pos.
Which part doesn't work? Are there any logs?
It logs the fixed virtual camera pos instead of the touch world pos
The weird thing is that I do get the correct screen pixels pos when I don't use ScreenToWorldPoint but it's just fixed on those coordinates when I add that.
Does the value not change regardless of where you have touched on the screen?
Are the values always the same?
yes
Just to verify, try logging the position of first touch.
Does the value change depending on where you've touched the screen?
But the camera converted value doesn't? That's strange.. it should convert your screen coordinate to world coordinate relative to the camera.
No way XD
I found the issue
Feed in the z value. firstTouch.position returns a Vector2 type.
what is the z value used for the parameter in ScreenToWorldPoint?
I had my camera set as perspective instead of orthographic 😅
yeah, depth matters in 3d (perspective) mode . . .
Has anyone connected a bluetooth device using Unity from android platform before?
Don't ask if someone's done something before, just ask your question - coding channel.
actually, do you know how could I make it work with my camera set as perspective?
pass in a Vector3 and assign a value to the z axis . . .
Help with Events and Listeners
Is this fine if I want to achieve a 2D movement in 3D?
Gave ChatGPT a try, it suggested to use AndroidJavaObject 👀
Whaaat? Why am I getting a y coordinate if it's set to 0?
you supplied the wrong value. the positon.y is in z value, and y is always 0.
I would suggest do this step by step. First, let's reference the camera. Second, create a new vector3 variable, plug in the position x and y into the correct parameters. Then supply the camera's far plane into the z parameter. Last, call ScreenToWorldPoint method afterward.
I think I got it working
this is what I did
now it's better but there's still a small offset in the position. I think it has to do with the z value (cam.nearClipPlane) of the touchScreenPos, but I don't know how to fix it
Why are you doing touchscreenpos? You're taking the vector2 and going STRAIGHT out to the nearClipPlane (which wouldn't follow the perspective) which gives you a world point. Then you use that world point to get another world point.
I think I'm just confused. I see that was nearly a suggestion (but they said farclipplane). I don't understand it, but if it's getting closer to what you want then before... then... I dunno lol
What do I have to do instead?
Why can't you just use the Touch.position in ScreenToWorldPoint? or raycast out if you're trying to hit a terrain or something. I didn't really see the issue you had at the start so maybe I'm way off base
Ah, because screentoworldpoint takes a vector3.... hmmm
Ok, the docs literally tell you to do exactly what you did
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
EDIT: Ok, forget everything I said lol. Sorry
This sounds like an X/Y problem, where you explain that your code doesn't work, but then now that it's working again, you ran into another problem we're completely unaware of. What doesn't work, and what should work.
Can you further explain this to me ?
So, when you're gonna play your transition animation, you want to move all the cards to the left or right. In this situation, if you only have cards that fit in the screen, you'd have an empty space left when a card should be. Another card outside the bounds of the screen would prevent that.
Yeah, with enough cards that's not a problem
Thing is, how do you make it so it's a smooth transition in the update of the data in the card
Because you either update it before the movement, or after the movement and both look kinda clumsy
Should be unnoticeable if you snap the cards back to their place and update the data in one frame.
I mean it works, but the transition for the movement of the cards (which takes around 0.5 seconds) had to be done with a coroutine so it doesn't just snaps things and has the time to do things properly, but that brings the problem that you have to wait 0.5 seconds between each scroll otherwise the coroutines won't be able to keep up
Oh, I thought that was the idea. If you want to have a continual scrolling, this approach might not be great.🤔
In this case you might need some kind of pooling system, where you take cards from the pool and place them where new cards should appear, while putting scrolled cards back to the pool.🤔
In which case I guess we're back to the point where you need to move the cards physically instead of just faking it.
Yeah
I pondered about that
What I figured is that
I can set a margin to where cards are moved back to the other side
Let's say I have 7 cards with a separation of about 300, so the middle would have 3 cards to each side, that's 3 * 300 = 900 units
So any card that goes past 900 units gets set back to -900
Same to the other side
That way you just move cards left to right and correct them if they go past the margin
Yeah, that should be fine.🤔
idk why I didn't figure that earlier
but oh well
Back to the drawing board I guess, didn't establish any flow managment program like git, so gotta code it again 🤣
Maybe it's a good opportunity to do it.😅
I detect ground angle but how can I then slow the vehicle when it drives uphills?
The issue is speed is an incremental value that grows according to input
But if I reduce the speed in one-frame/update(), it will continue being reduced forever, even though the speed penalty from that uphill shouldve been already applied
I think what i need to do is to cache the ground angle. and also cache how much I already used of it to slow down the vehicle
- This way i wont apply penalty for uphill driving more than once, at least until the angle changes
- but unsure when should i reset it
Maybe there are other ways ?
This is the concept so far, should be ok, ill code it
- store ground angle
- take from it by reducing vehicle speed
- add to it when ground angle increases
- remove from it when ground angle decreases
I think your speed and angle should just both exist stored, and angle shouldnt directly reduce speed but just be represented in the final equation.
Storing more like "how much already slowed the vehichle" doesnt exactly make sense
Like vehicleSpeed += speed * (some 0 to 1 value based on the angle) * (any other factor)
That 0 to 1 is arbitrary as well, it could be 0.5 to 1 or whatever you want the gameplay to feel like
i see yeah your idea is better thanks
Hi
public class ABDropdownAttribute : DropdownAttribute
{
}
public class ABDropdownAttributeDrawer : DropdownAttributeDrawer<ABDropdownAttribute, string>
{
protected override ValueDropdownList<string> GetDropdownList()
{
var type = typeof(ABFields);
var properties = type.GetFields();
var list = new ValueDropdownList<string>();
foreach (var propertyInfo in properties)
{
if (propertyInfo.FieldType == typeof(int))
{
list.Add(propertyInfo.Name.ToSpacedCase(), propertyInfo.Name);
}
}
return list;
}
}
[Serializable]
public class ABFields
{
public int a = 0;
public int b = 1;
}
Can you please tell me why this code does not show me the list of fields in the inspector?
im using a ray layer mask but despite the child of my parent being on a layer that shouldn't be hit its blocking the collision of the parent, how can i fix this?
Show code
You're doing something wrong with the layer mask then
I have:
public ISomeInterface someInterface
But the slot does not appear in the inspector for me to drag-n-drop an object with a script that implements ISomeInterface.
Is it supposed to, and if not, how can I have something akin to this functionality?
I believe you would need some custom editor to actually drag something to the interface slot. Some implementations seemingly exist online but unsure of if they're good
I believe you can also just GetComponent with the interface. so you just need a reference to the object you want it on
You could probably try using Serialized Reference
Hey guys, I'm having trouble adding OnClick.AddListener to instantiated buttons, apparently their events are not triggering. Is there a way that you guys know about? Thank you.
How have you been trying to add them currently?
InfoCard_UI_Comment comment = go.GetComponent<InfoCard_UI_Comment>();
comment.Initialize(messages[i], false);```
I instantiate the prefab, get the component and call an Initialize function that inside is the
``` likeButton.onClick.AddListener(OnClickAction);```
Sorry for the indentation it came a bit odd
No worries on the formatting at least its in a code block so a bit easier to read - im guessing messages[i] fill your OnClickAction param?
Well yes, it is indeed getting to the likeButton.onClick.AddListener since when using the debugger it gets there but when clicking the object whatever is inside OnClickAction is not executing
I'm guessing it looses reference somehow but Im unable to understand the why
How are you setting messages[i]? Does it do a Debug.Log or similar to confirm if its firing? Would it fire if you just passed for example delegate { Debug.Log("test"); } ?
are you doing this inside of a loop?
@strange ferry if so, you may have a closure issue. you need to cache i to a local variable and use that instead . . .
var index = i;
comment.Initialize(messages[index], false);
Sorry for the late response, I fixed it, I was making two different objects, one listened to the event and the second one was a copy of the first one but it wasn't able to listen to the event, thanks everyone.
humanInput.OnLeftClick += () => playerEntity.Shoot(0);
I will have many subs and unsubs like this and to many different entities at that. How do I unsub without creating a separate method for each combination of entity and the int argument?
You need to subscribe to an actual method without the arguments, if you want a proper unsubscribe
So you need to subscribe like this for example
humanInput.OnLeftClick += Shoot;
void Shoot()
{
playerEntity.Shoot(0);
}
Then you can do humanInput.OnLeftClick -= Shoot
But I will have like tens of these methods in that case
Otherwise you have an anonymous function and it's unlikely that that will work since there is no proper reference
You can also just do playerEntity.Shoot, and have that parameter as optional
OnLeftClick doesn't have a parameter
I was talking about the parameter of your shoot function
How do I choose the proper parameter then? It's supposed to be 1 for right mouse button
You could, for example, create some methods like HandleLeftClick and HandleRightClick which then call into the corresponding Shoot(0) or Shoot(1) methods
Or just get rid of the parameters of the Shoot method if possible, that would probably be easier to read as well, for somebody that doesn't know your project it's not clear why Shoot takes an int parameter in the first place.
Maybe do something like ShootPrimary and ShootSecondary
you need an actual method to sub and unsub . . .
I am having troubles getting the current control scheme in Unity's input system.
I wrote down everything here in this Reddit post. Does anyone know what I am missing?
https://www.reddit.com/r/Unity3D/comments/16cctze/having_troubles_getting_the_current_control/
As far as I know "current control scheme" is only a thing for the PlayerInput component:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_currentControlScheme
I have no idea what the code you shared is supposed to be doing - it doesn't seem to attempt to get the "current control scheme" in any way
it also seems to just be trying to print an uninitialized array and an uninitialized string
hello everyone, can anyone explain how RaycastPadding.Set() works(if it does at all)? i'm literally doing this
GetComponent<Image>().raycastPadding.Set(-400, -150, -400, -1450);
Debug.Log(GetComponent<Image>().raycastPadding.x);
and get a 0 in the console
if i replace the padding with the padding of another image it does work, but i just wanted to know why this one doesn't
you probably need:
Image image = GetComponent<Image>();
var padding = image.raycastPadding;
padding.Set(-400, -150, -400, -1450);
image.raycastPadding = padding;```
to be honest though I don't even know what raycast padding is and I don't see it in the documentation