#archived-code-general
1 messages · Page 187 of 1
If you have 1 SO mapped to 1 instance type, you can have something like CreateRuntimeInstance virtual method on your SO. And inside of each SO type, create the specific Runtime instance and return it.
yeah the better option of those suggested so far would be to just use a Scriptable Object for each skill type and you can drag it in. otherwise you could use something like SerializeReference and some custom editor stuff to serialize instances of the class you need.
vertx has a SerializeReference Dropdown package that would be nice for this
just use a Scriptable Object for each skill type and you can drag it in
I do have a unique SO per skill, where are you suggesting I drag it?
oh wait, i think theres been a miscommunication
what do you mean by mapped?
public override Type MatchingSkillScriptType()
{
return typeof(ScytheSlashNormalAttackSkill);
}
every skill has a unique class
something like this?
i meant use a scriptable object for the behaviour, instead of using a scriptable object just to instantiate a poco. you know, like i suggested earlier
this would save you the trouble of using reflection and the Activator class to create an instance of your desired class because it would already exist
Mapped as in there is one unique runtime type for one unique SO type.
thanks
Instead of getting the type you can get a new instance of that type right away.
yes i'm aware of how you currently have it set up. at this point you're either willfully ignoring what i'm suggesting or just not getting it so i'm giving up. good luck and have fun with your reflection since you're hellbent on using that 🤷♂️
Homie ima be real
if your not feeling it you don't have to keep helping
I appreciate it but the tone is a little weird
what if you want to change variables of class in runtime?
do you suggest creating an instance of scriptable object
well presumably the instance of the SO would already exist
Well, what if you have 2 skills with the same function, but different params?
Like a fireball and super fireball with double the range, damage and a fancier vfx?
of course changing the properties of a scriptable object asset works differently in the editor as opposed to a build so there would probably be a bit of weirdness from that, but that doesn't completely invalidate the suggestion. nor does it mean they still can't use a POCO for the behavior part, but they'd have that SO that already has the data they need instead of using reflection and strings to create the type at runtime
the trick is to have a poco class as a field within the SO. it holds the default data of the SO, and you create a new instance using its data so you can change that instance during runtime . . .
in the context of the game i'm making that's rare enough to where i would prefer them to be consistently rooted vs. the very small amount of inherentence
But the issue is in my scenario every type of instance is different
😛
isn't that normal?
sorry, not sure what you mean by that . . .
I mean, if reflection solves it, then go ahead and use it. If that's the case, then your question was answered long ago.
well from past experience you'd have a setup like
ItemData: SO
PickupData : ItemData
LootData : ItemData
Item : POCO
Pickup : Item
Loot : Item
but this is
Skill : SO
OneSkill : POCO
TwoSkill : POCO
etc. etc.
this seems better than using activator and dealing with types
Looks like it could be the best option for me yeah :/. the help has been appreicated
yeah, and the SO holds the poco class. this makes it easy to copy or create a new instance of the SO values to update and change during runtime . . .
seriously, take a look at the package i linked you to. that is probably going to be the best/easiest option for you here and won't require any runtime reflection
https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
I'm doing research now! People keep responding so I keep responding back 😅
what relation does Skill and OneSkill/TwoSkill have in common?
Skill is more data based (name, desc, icon etc.)
OneSkill & TwoSkill store game mechanics with completely seperate, running code
Damn, that's great. I was doing my own implementation of that with OnValidate and it was clunky as hell.
do you mean change variables in so and copy from poco to return to default or change variables in poco and copy from so to return to default
im kinda confused
you set the default variables of the SO (you're actually assigning the values of the poco within the SO) in the editor. during runtime, you create a copy or new instance using the poco from the SO. this ensures the SO stays immutable while allowing the user to edit their copy . . .
I don't fully comprehend when the instance of the poco class is created with this? As soon as you select in the editor? im probably completely misunderstanding
yes
Does that mean I need to make a copy of it at runtime or do I need to reset it's values when the game stops playing? does this instance ever die?
Hey! I'm using A* to control enemy pathing, Just curious how to give all enemies the players transform from a prefab, whenever the player dies they also lose the instance of the transform to reference which is mucking everything up
prefabs cannot reference scene objects and if the prefabs reference another prefab it isn't automatically changed to the instance in the scene. so you'll have to pass the reference to the player's transform when you spawn the enemies. I'd also recommend an event or something for when the player dies/respawns to update the reference. or just don't actually destroy the player but reset it's position/health/whatever instead
here's some info about how you can pass a reference to an in-scene object when you spawn a prefab: https://unity.huh.how/programming/references/prefabs-referencing-components
oooo thank you v much
each time I load up my unity project in omnisharp I get a lot of errors about
Analysis of document float4x3.gen.cs failed or cancelled by timeout: The operation was canceled.
This error happens for I think all of the .cs files in com.unity.mathematics@1.2.6 as well as some others. Is someone familiar with this?
Hi guys, having a little problem with a Collider.
Trying to register when my "bullet" collides with anything.
Do I have to do anything besides attaching a CircleCollider2D to my "bullet" (and rigidbody for the physics)
and then, In a script, attached to the "bullet", use the "OnCollisionEnter" method?
Thank you, I'm stupid!
I used:
OnCollisionEnter(Collision collision)
and should use:
OnCollisionEnter2D(Collision2D collision)
you might wanna double check that resource i linked again 😉
Oh, now Im really stupid.. thank you
Another question. I'm on Linux and are using VS Code. In "regular" VS, one get's a little help from Intellisense.. I think I have all extensions needed for VS Code to make it work as VS, but the color scheme and everything doesnt really work as i thought it would..
!vscode
Sorry, I missed this, thats in the rules right? Not having a very good day here! -_-
the IDE configuration stuff is in #854851968446365696 which is honestly probably the least read channel in the server 🤷♂️
just be warned that vs code can be super finnicky with unity. so if you happen to have access to Rider i'd recommend using that instead
Oh, I'll check Rider out. Thank you very much for your input!
Im trying to set the value of my slider to my progress variable but GetComponent seems to return null, the image shows the chargebarImageObject object
chargebarImageObject.GetComponent<Slider>().value = progress;
am I missing something here?
are you sure chargebarImageObject is this object
100%
i mean ik the chargebarImageObject isn't null so im guessing its the getcomponent
check? log the result of GetComponent
log them both, or use debugger
Is it possible that Slider is referencing a type other than the UnityEngine.UI one?
Otherwise I'd assume references are lost at one point
thats what i thought at first too but seems to be the right one
UnityEngine.Debug.Log("chargebarImageObject: " + chargebarImageObject);
UnityEngine.Debug.Log("chargebarImageObject.Slider: " + chargebarImageObject.GetComponent<Slider>());
try to get all the components to see what components the gameobject has.....
i mean im also doing this and it works just fine, its the slider that doesn't want to work
chargebarImageObject.GetComponent<Image>().fillAmount = progress;
have you tried.. removing and readding the Slider? 🤷 this is weird
so i just recommend you log all the component on that GO
you're sure this is the only object with this script in the scene? @obtuse flame
no there are multiple, is that a problem?
i mean this is on my player prefab but its a multiplayer game so there will always be multiple
just did this and still not working
are there instances that have chargebarImageObject don't have the Slider?
don't think so but ill check
foreach(Component component in GetComponents(typeof(Component))) {
Debug.Log(component);
}
```are you using this?
this is what it prints, the red thing is a in house network component that im not sure if im allowed to share so just crossed it out just in case.
seems like the slider isn't being added at all, might be becus of the network stuff, im gonna ask my colleague
What part is actually giving out null, we havent seen the actual error/line number tbh
This might just be something simple and not what we think the error is
it doesnt have slider on it
Ah didnt read that last message before writing nvm
you can crop the image so you dont expose it to us
How do I bound the line between the two axes so that it snaps to one of them
First I thought of doing this:
private void DisplayArrow()
{
Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 currentPos = Vector2.zero;
//Detects if the cursor is within bounds
if(cursor.transform.position.x <= xAxis.position.x || cursor.transform.position.y <= yAxis.position.y)
{
isWithinBounds = false;
currentPos = new Vector2(cursor.transform.position.x, cursor.transform.position.y);
}
else if(cursor.transform.position.x >= xAxis.position.x && cursor.transform.position.y >= yAxis.position.y)
{
isWithinBounds = true;
currentPos = new Vector2(cursor.transform.position.x, cursor.transform.position.y);
}
if (isWithinBounds)
{
lineRenderer.SetPosition(1, mousePos);
}
else
{
//print("outside bounds");
//lineRenderer.SetPosition(1, currentPos);
}
}
But it's a frame too late
or too early it varies
I thought of using colliders but I couldn't figure out a way for that either
What do you mean by snapping to one of them? Do you want it to snap to a grid? Do you want it to stay in the bounds of the the x y lines or do you want it to snap to the axis it is the furthest on?
What exactly are you trying to achieve?
will JsonUtility not deserialize to decimal? float or double seem fine but not decimal
Ask yourself, does Unity serialize it if you have a serialized field of that type in a MonoBehaviour? JsonUtility uses the same internal serializer as Unity, and so it supports (and doesn't support) the same types and features as Unity.
And if you don't know the answer to that either, the answer is no, Unity doesn't serialize decimal.
Yeah the manual is unclear though... mentions double and 'basic types'. Anyway seems unsupported in all cases on trying
ah decimal is not a primitve data type - well everyday is a learning day...
Is there fast way to spawn bunch of those blocks and have them being simulated so they collide and bounce with ground?
These are spawned when blocks explode/trees fall down, for example.
And yes I am pooling them.
Right now the performance is ok but not so ok when there is hundreds or thousands of blocks, resulting of large explosion
Also right now they use box colliders & rigidbodies and I would like to keep them 3d rather than rendering them flat 2d
So there's a reason Teardown has a custom built voxel physics engine. This isn't really going to be feasible with Unity's built in physics engine.
Ok so I need to spawn less blocks or not spawn them at all?
I was thinking just creating mesh for the destroyed object and make that mesh fall for a bit and then disappear
that entire game is custom
it's wild
Sorry for not clarifiying, I want it to stay within the bounds of the x and y lines
I got the detection to work but the line updates later than the detection, not on the same frame
Here's what I mean
The line doesn't follow the mouse exactly, it lags behind
Instead of checking if the cursor is outside the allowed area and not updating the line if it is, you can clamp the position of the cursor to the allowed area and always update the line.
Ooh that's a great idea, thank you!
Goddamn that worked beautifully
is there a good way to intercept the effect of an areaeffector2D so an object can only take force from one point effector of a given tag at a given angle?
or is that something that needs to be done via script, replacing the area effector?
What I was saying is that if you want to do this style of game well you'll need to write a custom physics engine if not a whole custom game engine.
But as for making temporary objects that will disappear, maybe just look into a particle system
Or VFX Graph
thanks
does anyone know how to modify contacts? I'd like to make my own effectors to work better for my purposes.
or know of reference material to learn
alternatively, if I could get source code for effectors in Unity, that would also help tremendously
What do you mean by "effectors"?
Are you referring to the effector components in Physics 2d?
Also note this has been fully released and isn't experimental anymore
cool
ty praetor
my goal rn is to make an area effector that tries to avoid double counting with other area effectors tied to gameobjects of the same tag (in one frame). My next goal after that is to make a platform effector that actually works with tilemaps, so I don't need to instantiate 5000 gameobjects just to have some semisolid platform blocks.
this is preprocessing?
It's modifying the contact before it's resolved, if that's what you mean. So you can, for example, tell it to ignore contacts so the colliders go through each other.
How can I remake an OS like windows 95
off topic
Hello, for a project I’m working on I need to track the position of a real life object and have an asset mirror the position of the real life object in real time. The idea is to have a stationary camera connected to the PC which will get the live feed of real life object’s position. I’ve been looking into Unity’s AR Foundations to achieve this but I haven’t gotten anywhere yet. I’m new to Unity and I was wondering if I’m on the correct path and what I would need to do or if this is something that has been done before and I can get a bit of guidance (from what I’ve gathered, I can’t find any similar projects on the internet)
`public class LevelTransition1 : MonoBehaviour
{
public GameObject EnemyIcon;
public GameObject TreasureIcon;
public GameObject Arrow;
public GameObject Background;
public LevelManager LevelManager;
public GameObject IconContainer;
private void Start()
{
moveArrowAboveIcon(IconContainer.transform.GetChild(3).gameObject);
}
public void ShowTransition()
{
LeanTween.moveY(Background, 540, 1f);
}
public void moveArrowAboveIcon(GameObject EnemyIconToMoveTo)
{
Arrow.transform.position = EnemyIconToMoveTo.transform.position + new Vector3(0, 100, 0);
}
}`
Im trying to move the arrow above the icons but it always stays at the left side of the screen no matter which icon i give as input into the function moveArrowAboveIcon. Am i missing something obvious?
Is there a version of this for desktop?
https://docs.unity3d.com/ScriptReference/Handheld.PlayFullScreenMovie.html
guys I am having a hard time conceptualising an answer to my problem can someone help me with that please.
so what my problem is, im making a detective game and each object that has a script called clue in the script a description of the clue is made. I need to add each clue description to a JSON file. I was able to follow a tutorial on writing to a json file but it doesnt work properly because its overwriting each clue description to file. can someone please help me re write the code so that it adds each clue description the json file.
public class Input_Handler : MonoBehaviour
{
[SerializeField]
private Clue clue;
[SerializeField]
private string FileName;
List<Input_Entry> entries = new List<Input_Entry>();
public void Add_Clue_Description_Text()
{
string Clue_Description = clue.InteractionDescription;
Debug.Log("Clue_Description " + Clue_Description);
entries.Add(new Input_Entry(Clue_Description));
Debug.Log("entries.count " + entries.Count.ToString());
Clue_Description = "";
File_Handler.Save_To_JSON<Input_Entry> (entries, FileName);
}
}
``` so this class is attached to multiple objects and the problem is because they are attached to multiple objects each object has a unique array called entries and is writing to the same file so it keeps getting overwritten how can I fix this ?
Can anyone help me figure out why the Steam .NET SDK doesn't recognize any achievements?
With this code I get an output of 0 achievements despite making an achievement in steamworks:
if (!SteamManager.Initialized)
{
Debug.Log("Steam not initialized");
return;
}
uint count = SteamUserStats.GetNumAchievements();
Debug.Log("Achievement count: " + count);
I have Steam running and I've set the app_id in steam_appid.txt
Steam says the game is running, when I stop it, it closes Unity
SteamWorks initialises correctly, at least it tells me it does
The achievement has both icons set correctly
I've tried restarting steam/unity
Do I need to make the game public/visible in some way? I'm pretty sure I don't need to publish anything yet
I tried running it in a build as well but the same thing happened
Steam overlay is also not working but not sure if it should yet
I also call this code in Update before any achievement code runs:
if (SteamUserStats.RequestCurrentStats())
Debug.Log("Steam stats received");
else
Debug.LogError("Steam stats not received");```
Hopefully someone can help me thanks
Edit:
I had to publish everything first, damn it
📃 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.
so I need to write to a json file that is attached to multiple objects
Hey does anyone know how to create individual logic for methods within a ScriptableObject? So for example I want A ScriptableObject containing data for each Enemy and they all have the Attack method that can be called from the EnemyController but I want to make each Attack logic different for each ScriptableObject
You need multiple scriptable objects (can make all of them inherit from a base class so you have common abstract methods), or don't implement the methods in the SO, but instead expose an event that you can link to a method in one of your scripts
anyone???
you made "entries" an instance field so each time you save it only includes the object that saved it, maybe just ditch the entries field and load the existing list from the json file before adding the item and saving it back?
soz so should I still have a variable called entries?
a variable not a field i guess
of type input_Entries?
a list, i guess you would have to do something like var entries = File_Handler.Load_From_JSON<Input_Entry> (FileName);
why load from Json and not save_To_Json???
well atm you're saving over the content and losing the previous entries every time right? to append to the list you'd need to load then save
oh so load the file with the code you gave then do this
entries.Add(new Input_Entry(Clue_Description));
then do this
File_Handler.Save_To_JSON<Input_Entry> (entries, FileName);
so read, write, save?
yup!
you could probably find more efficient ways to share the list around between scripts, but that's a simple fix
ok thx
Ok guys I need your advice and opinion about how to structure the code of a 2d Platformer in a nice way. Most of the code I find is simply a controller script that contains all movements in one script such as horizontal movement, jumping, falling,etc.
Now that is quite easy to build up, but I think the code is quickly getting messy if you have additional abilities such as dashes, double jumps and so on. In addition distinguishing between the single states is not that easy and beautiful.
Now I lost my heart somehow to using a statemachine that manages the changes from one state to another (similar to what the animator does with the transitions). Therefore each state (such as IdleState, RunningState, JumpingState, etc.) is then put into a separate script file that contains a state class. The base class methods are always executed and can perform common actions that are needed for almost any state.
But there are downsides aswell: The states of a statemachine are no monobehaviours and thus I cannot use the [SerializeField] option to configure my script easily. Also transferring data from one state to the other is not that easy.
Now my question is: Do you see a way to get rid of the statemachine downsides? What is your opinion about this? Sorry for the long explanation
I have no clue what is going on or if i am going about this right i am trying to move playerObject out a parent object. i put them in .. but this playerObject.transform.parent = transform.root; Line of code moves them out of the object i am happy with. but the Player Positioning is incorrect Will not center with the scene it created its own center.
That wouldn't move it out of the parent, but change the parent to the root parent (which may be the same object). So you are probably in local coordinates
That what i was just thinking..
Is the root object at world origin?
0,0,0 on your object is the position of its new parent
SetLocalPositionAndRotatio i used this line after it was moved.
Ok, so that would also be local space. What are you actually trying to achieve?
Yeah that was the issue I changed it to SetPositionAndRotatio
What i was trying to do is enter an object like vehicle and exit out next to the vehicle.. i moved everything including player object in to an object attached to the vehicle.
Let me edit this...
Ok, so don't you think you want to do
playerObject.transform.parent = null;
?
Because wouldn't the root be something to do with the vehicle?
Then get an offset from the vehicle position for the exit position
Does that move the object out of everything. and its placed in the main scene
Yes
Haa i need to keep note of this null.. that worked even better.
Thanks for the suggestion
i might have experienced a bug? so i have a sound thats on and everything is setup but of some reason it isnt playing, i found out that if i right click the audio source component in the inspector it starts playing but i have no idea why, can anybody explain why?
im a 10X dev, ask me anything
thx it worked 🙂
How to write if else sir 🤓
I learned c# fully but still I can't create my own movement script
Go to the texture and make it read/write
(2d) I'm trying to make a camera follow script and the camera goes blank because it goes into the player
Don't crosspost.
Srry
Why is that?
That's impressive, I've been programming in C# for 15+ years and I still don't know it 'fully'
And it's no wonder you cannot create a Movement script, that is not C# it is the Unity API's
Reloading a scene in runtime completely breaks events for me, i get a missing reference exception where it's missing a reference to the script itself when it tries calling the event
using UnityEngine;
using UnityEngine.Events;
public class EnemyClear : MonoBehaviour
{
public UnityEvent OnRoomClear;
private void Start()
{
Enemy.OnAnyEnemyDeath += CheckRoomClear;
}
private void CheckRoomClear()
{
print("check");
if (transform.childCount == 0) OnRoomClear?.Invoke();
}
}
so in this case its throwing "The object of type 'EnemyClear' has been destroyed but you are still trying to access it." but only after i restart the level
So you have something subscribed to OnRoomClear which has not unsubscribed in OnDestroy
well the only things i subscribed is a song change and turning off the lights through the inspector
right becuase you never unsubscribed
so you still have a destroyed object listening to the event
Could also be a subscription to OnAnyEnemyDeath
console says it's in the CheckRoomClear method, or is it still possible its an issue with that
it's your CheckRoomClear function trying to access transform
but on the destroyed copy of the script
hence the error
to fix it - properly unsubscribe in OnDestroy
yes,
EnemyClear needs an OnDestroy method which unsubscribes CheckRoomClear from OnAnyEnemyDeath
is there a writeup somewhere that gives guidelines on where to place specific behaviors/methods ini the update order?
like should my state machine checks happen at the beginning of the simulation? or at the end?
What would you check at the end of the simulation that would make sense to check at the start instead ?
wdym by "the simulation"?
Best practice is to write your code in a way that it doesn't matter what the script execution order is to whatever extent is possible.
When not possible, best practice is to explicitly run your code in the desired order through some kind of orchestration function/script
this logic doesn't really apply in general tho?
In general this is the advice i'd give
Make sure that you keep the z position when setting the camera position. This can be achieved e.g. by using the following code:
camera.transform.position = new Vector3 (player.transform.x, player.transform.y, camera.transform.z);
The 3D Vector code also applies if you program e.g. a 2D platformer using the 2D extension...
Is is better practice to control disabling/enabling of game objects themselves or components of game objects
they each have different uses and are appropriate at their own times
Ok thanks
is there a way to spawn heavy prefabs in scenes so that the time dont freeze or any lag like can give the preload time or something
Instantiate them in the loading screen
You could also divided them in smaller parts
but how u get that is it loaded or not
However, you shouldnt really have "heavy" instantiated object out of loading.
I mean, when you do your loading. When you load the scene.
so i have only one scene so i am trying to do all the stuff in one particular scene
You shouldnt use only 1 scene.
Oh nice, unity has a lesson about pooling
This may help
<link>https://learn.unity.com/tutorial/introduction-to-object-pooling</link>
so basically i have multiple levels like can be 100+ so i cant really make 100 levels
Pretty sure this tutorial is not up to date.
Ah dang ok. Didn't really look closely
So, you load them in the loading screen.
basically two scenes one for ui and one for all the levels?
Just keep it disabled and enable the object when you need, while having it already placed in scene or spawned in awake or something
No.
You have a "first scene" that is basically empty that only has 1 objective, loading the rest of the game.
You then either transitionate to a MainScreen or you instantiate a UI canvas.
no that is ok but i dont want to load 100 of levels at once like the scene will be very heavy i guess
Which then go to the appropriate scene whenever the user click on "Play"
Yes, you do not want to have all level loaded at once. It wouldnt scale well.
Are these objects you are spawning your entire levels?
That is considering that you have a proceduraly generated level.
so if instantiate a level in awake or something will it also get load if i use async ?
No.
it should already be present in a level?
However, the lag spike will be hidden.
And, you should load it in multiple part, given that it is proceduraly generated.
Otherwise, just make 100 scenes.
not doing proceduraly generated or something
Then just make 100 scenes.
Why ?
of project like if we make 100 scenes
Why would be larger than 100 prefabs ?
Scene a large usually because they contains more things, however in your case, the scene will be equal to a prefab
So, no it will not be larger in size.
Yes
👍
Also, async will only load the resource asynchronously, you will have the instantiation sync.
Even if there was a difference, I think 100 scenes is way better because editing these all as prefabs sounds extremely tedious
hello, does anyone know a better way to handle all of this? i wrote this late and forgot if there was any function (relating i think) to mathF that shortens all of this by a lot
jesus
isn't tjhis just a simple math function?
You gotta be kidding
Seems like the condition and return value are directly related
i forgot it somehow
use a loop i guess to check and return
Like this is literally just subtraction
definitely no need for a loop
yeah it's like
return Y_Axis - boundsMaxY - 1.54f;``` or something
i'm trying to smoothly transition a blend tree (for a ladder animation, going from climbing to dismount_1, 2, ect) and from all my ideas i decided to write that
i'll try this rn
i mean I didn't think that hard about that formula but it's basically something along those lines
what you hve no is definitely going to not be as smooth as this (assuming this math is correct)
i'm gonna try that out rq and check if theres anything else to smooth it out
it works, gonna make it better in the meanwhile
what was the syntax of running a function if a bool is true
it involved =>
something with L ?
huh? you just use an if statement to check if the bool is true or not before calling the method
if (someBool) {
TheFunction();
}```
the => is lambda expression syntax
yes lambda
which ... does not do what you said
I think there's probably some missing context here if you are associating lambdas with that
Interactable _int = other.GetComponent<Interactable>();
if (_int != null) { _int.Interact(this); }
}```
i want to turn this in lambda
why
also just use TryGetComponent then you can combine the getcomponent and null check into one line that goes right into the if statement
It doesn't make much sense to use a lambda there
Why is that even though I'm setting this UI element to the mouse position directly it's offsetted weirdly?
Code:
void ShowMagnitude()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
magnitude.transform.position = mousePos;
}
Video:
you mean the slight delay?
I have zero idea why it's not showing here wtf
No not that
bruhh
Here
Game view
one thing is that UI/Canvas space is not the same as world space
Yes but it's working here fine:
void SetPositionAtMidpoint(Transform toMidpoint)
{
Vector2 origin = arrowShower.lineRenderer.GetPosition(0);
Vector2 currentLineEndPos = arrowShower.lineRenderer.GetPosition(1);
Vector2 midPoint = (origin + currentLineEndPos) / 2f;
toMidpoint.transform.position = midPoint;
}
unless you're using Screen Space - Camera
LineRenderer is a world space renderered object
World Space
ah yeah in world space it should also be ok I think?
TryGetComponent<Interactable>(out Interactable _int) => { _int.Interact(this); }```
is this how you write it
are you using a perspective camera?
Oh sorry, this is the video in question
remove the => from that because it's 100% pointless
and then you wrap your tryget call in an if statement
No, orthographic
if (someObject.TryGetComponent(out Interactable interactable)) {
interactable.Interact(this);
}```
Setting the position direclty for the V works fine but not for the parent of the 2 text elements
why you g uys hate lambda
also you have yet to explain why you think a lambda is necessary here. it doesn't seem relevant at all to what you are trying to do. do you even know what a lambda expression is?
maybe use the world space TextMeshPro instead of a UI element?
it seems automated
I love lambdas, when they are appropriate
this does not call for a lambda
well that just proves you have no idea what it is even used for
Wait, what?
@mystic ferry
GameObject -> 3D -> TextMeshPro
Holy shit thank you I didn't know that existed
TryGetComponent<Interactable>(out Interactable _int) => { _int.Interact(this); }```
ok can you tell me how to use lambda here
you don't use a lambda there because it doesn't make sense to
again, do you even know what a lambda is?
just tell me how to write it
I had just created a preset, and I want to apply it to tall the sprites in a particular folder(or game) is there a way to do this?
I have also made the preset the default preset. But, Im not sure how to apply the preset to sprites that have already been imported
in what sense do you want to use a lambda here?
there is no way to write it because that's not how this works
how does it work then
a lambda is just a way to write a function inline without giving it a name
aka an "anonymous function"
they are not a replacement for if statements
you can use a lambda anywhere you can use a delegate
delegates are just variables that can refer to functions rather than holding regular data
so a lambda is creating a function?
yea
Yes
then why not say that in the first place
e.g.
// put a function in a variable:
Action myFunction = () => Debug.Log("Hello");
// now I can call the function:
myFunction();```
why insist on a lambda in the first place when multiple people have told you that isn't what you need?
I used the lambda here to define the function inline
I thought you said you knew what it was. We said over and over to not use it
But I could have defined the funciton normally too
i am instantiating a ui text but for some reason its not taking the position of its prefab for some reason even though I am setting it to
public class Add_Clues_To_NoteBook : MonoBehaviour
{
[SerializeField]
private string FileName;
[SerializeField]
private GameObject ui_Text_Panel;
// Start is called before the first frame update
void Start()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.X))
{
AddCluesToNoteBook();
}
}
void AddCluesToNoteBook()
{
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, transform.position, transform.rotation) as GameObject;
new_UI_Text_Panel.transform.SetParent(GameObject.FindGameObjectWithTag("Left_Page_Panel").transform, false);
}
}
why is it in this random position ?
you culd have simply said that lambdas create functions
The best way to instantiate child UI objects is like this:
Tranform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);```
Ui use rect transform, which doenst align with transform componenet
thanks will try
oh so change transform to rect transform?
won't make a difference
Btw do you know how to fix the slight delay?
just FYI as GameObject as part of your Instantiate line is pointless and has been so for years since the generic Instantiate method was introduced
how can i fix the <T> ? its with darker color with error telling me it can be simplified
Just remove it
It is unnecessary
it's not fixable. It's because the mouse has special hardware rendering support on your PC, but the game runs at a much lower framerate than that
you don't need it
delete it
do it like my example above
ui objects wont show unless it's under a canvas. Thier positioning dont correlate
line 26400 "user did not grant permission"
Ok thx, I don't mind it anyways
ok thanks
you can just remove it. the type is specified in the local variable declaration inside the ().
also you probably want to be calling TryGetComponent on the other collider 😉
So do I run as administrator
can someone tell me how to do this?
wait but the panel is under a canvas the the text will be under a canvas too no?
yes
Okay cause I did that and it didn’t work
I don't think you can do this - I think it's only for new assets
in that case yea
even through script?
wait nvm
read the "Applying settings from a Preset" section here:
https://docs.unity3d.com/Manual/Presets.html
i read it
this worked I just need to make it so adds a text panel below instead of the same place so I guess increment transform
@mystic ferry I’ll try to go through my administrative settings and figure it out. Thanks for the help
I want toapply to entire folder, not individuals
select them all
apply the preset
done
you can change preset of folder
for reference when you go through logs you can ignore all of the info and warnings, the errors are the most important
what if folder has sub folders etc
you had some pipe issues earlier but the last error was a permissions error so I'd start with that
If you press this you can find all assets of that type in the project i believe
or maybe even in a folder
Looking at multithreading ... I mean Jobs in Unity. So if I have a large structure of say array of 1000 elements, I need to copy it over to the Job to calculate anything?
I fucking love you 😙
It needs to be a in a NativeArray or other native collection for a job to operate on it - yes.
Note that you can just use the NativeArray in your non job code too
so it can be the main source of truth for that data, rather than having to copy it around.
I'm sure I'm having a moment, but would the prefab variables (voltage, etc) not be shown in the prefab instance?
doesn't look like yoiu attached the PowerPylon script to it
Press Add Component and add the Power Pylon component to it
(and make sure you apply this change to the prefab as well)
Wait sorry
Looks like "Power Pylon" is not a component, it's a scriptable object
which is completely unrelated to prefabs
so I'm not sure what you're trying to do here
So I gave everything administrative permission. Same thing
if I remember, the log error said you had denied the UAC prompt, it still says that even when you run as admin?
So let's say I have a Simplex Noise generator, I cannot store references of it in the Job. Does it mean I must copy over all noise generator code to the Job to do this? Or do I need to convert everything to static variables to make it work? 
You'd need the simplex noise code to be Jobs compatible yes
if it uses managed objects right now it will require some adjustment
Ah yes that is what I'm doing. Basically at a high level I'm trying to create a power pylon object which is instantiated by the player on a grid similar to the old SImcity games, but that (which I put as a scriptableobject in here) should have variables connected with it and functions for things next to it on the grid
I know I'm fumbling this
At a basic level - change your PowerPylon scirpt to derive from MonoBehaviour - not ScriptableObject
then you can attach the script to the prefab.
it's also possible you'll have to manually edit permissions, I've had strange issues before where programs ran as admin still for some reason had all read/write perms blocked
for some reason when I try to shift the clue ui text a bit lower it ends up too low i think its becuase ui uses pixels and im using the transform
void AddCluesToNoteBook()
{
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
new_UI_Text_Panel.transform.position = new Vector3
(
parent.transform.position.x,
parent.transform.position.y + 0.00001f,
parent.transform.position.z
);
}
so how do I shift it down so it looks like this(image on the left) and not in middle of the panel like this(image on right)
Got it, thanks! I'll test it out now
you should use a vertical layout group to arrange these things properly, rather than manually adjusting positions in the code
ooooh didnt know that existed
I wish someone had told me about layout groups sooner. Same thing with grid layout groups for inventories
it felt like a hidden gem I stumbled upon when I first heard about them
super useful to read through these before doing UI stuff:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIBasicLayout.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIAutoLayout.html
thx will read now
It works just as I was hoping, thank you!
Yea, I right click, click run as admin and it doesnt load anything not even the hub. Also I went into properties security and Allowed all permissions so Idk what is wrong
Ok, thanks
I dont want to bother you all, but does anyone have experience with using authentication via Steam?
A little bit, what's the issue?
I cant get it to work, hold on ill get the code for you.
The problem is mostly that i just dont get what i should be doing from my current situation
I can only really help you're using the same implementation. I use
`using System.Collections;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Unity.Services;
using Unity.Services.Core;
using Unity.Services.Authentication;
using Unity.Services.Leaderboards;
using UnityEngine;
using Steamworks;
public class Login : MonoBehaviour
{
private string hex;
HAuthTicket ticketrequest;
Callback<GetAuthSessionTicketResponse_t > m_AuthTicketResponseCallback;
public async void Start(){
await UnityServices.InitializeAsync();
GetTicket();
OnAuthCallback(m_AuthTicketResponseCallback);}
void GetTicket(){
m_AuthTicketResponseCallback = Callback<GetAuthSessionTicketResponse_t>.Create(OnAuthCallback);
Byte[] ticket = new Byte[1024];
uint sessionTicketSize;
ticketrequest = SteamUser.GetAuthSessionTicket(ticket, ticket.Length, out sessionTicketSize);
Array.Resize(ref ticket, (int)sessionTicketSize);
hex = BitConverter.ToString(ticket).Replace("-", "");}
void OnAuthCallback(GetAuthSessionTicketResponse_t callback){
AuthenticationService.Instance.SignInWithSteamAsync(hex);}
}`
OK, so what I would say is that based on another plugin I once used there was something additional I needed to run in Update/FixedUpdate, RunCallbacks if I remember correctly. Have you followed the documentation exactly?
It, to me, looks extremely familiar even though you're using Unity's implementation.
Honestly, it may not be the issue, however I cannot see Unity starting up background tasks without your knowledge here.
`Callback<GetTicketForWebApiResponse_t> m_AuthTicketForWebApiResponseCallback;
HAuthTicket m_AuthTicket;
string m_SessionTicket;
void SignInWithSteam()
{
m_AuthTicketForWebApiResponseCallback = Callback<GetTicketForWebApiResponse_t>.Create(OnAuthCallback);
m_AuthTicket = SteamUser.GetAuthTicketForWebApi("unityauthenticationservice");
}
void OnAuthCallback(GetTicketForWebApiResponse_t callback)
{
Token = BitConverter.ToString(callback.m_rgubTicket).Replace("-", string.Empty);
m_AuthTicketResponseCallback.Dispose();
m_AuthTicketResponseCallback = null;
Debug.Log("Steam Login success. Session Ticket: " + m_SessionTicket);
// Call Unity Authentication SDK to sign in or link with Steam.
}`
This is what unity tells me to do
i have tried a couple youtube videos as well, but there isnt much documentation about this subject
I forgot to add the error code, silly me:
error CS1503: Argument 1: cannot convert from 'Steamworks.Callback<Steamworks.GetAuthSessionTicketResponse_t>' to 'Steamworks.GetAuthSessionTicketResponse_t'
Yeah, I cannot help you with the UnityServices side of things. I also can't really suggest move away from Unity-made stuff in the Unity discord.
But my question to you is, why are you trying to login? Is this a client -> server system?
The client has direct access to steam without keys etc
Im making leaderboards and i need names and stuff. But im using the Unity Leaderboard and if im correct that only changes names when I use authentication methods
Perhaps you're correct for the Unity services implementation, but every other Unity implementation (that I've used) doesn't require that.
I'm trying to profile something that is called a few times in a frame and this is happening instead of it just saying "called x times". Does that mean I'm not closing all my profiler samples with Profiler.EndSample()?
Doing GetAuthTicketForWebApi is pointless without an authoritive server checking if it is valid.
Client side cannot be trusted as you can edit/mod the game
Ill try it again, I used the normal authentication a while back with one of the new methods they made for changing names but it didnt work properly yet
You shouldn't have to do any authentication at all. You initialise steam and then communicate with steam.
yeah but I need it for the unity leaderboard, atleast the last time I checked
could be wrong, Im quiet new to services stuff
im gonna read the leaderboards docu again to make sure
yeah it needs authentication
Have you followed the tutorials at https://unity.com/products/leaderboards too?
Yeah, the leaderboards are all set up and can be entered anonymously because anonymous authenticating is way easier, but i need steam names hahah
:/
this is in the setup for leaderboards
I used this function last time and it did the job during private testing but didnt work when i let some other people play it:
UpdatePlayerNameAsync
Thats why i am seeking alternatives
Ill check it again though, and let some playtesters go at it when im ready
else ill be back 🫡 😎 👍
For me it works again, but ill need to put it into the demo now so other people can test it
why unity hasn't implemented their own email/pass login is a really dumb decision
I am trying to access all the instantiated ui text in my game and make each text equal to something different.
I know I will use a for loop to loop through each ui text panel but dont know how to access each element?
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
for (int x = 0; x< entries.Count; x++)
{
ui_Text_Panel[x];
}
Do you mean like
"ui_Text_Panel[x].text"
?
no doesnt work I get this error.
because the text panel has a description of a clue so each text panel is going to have a unique clue description
if I update if my player is grounded using OnCollisionStay/Enter/etc, then use that information in fixed update, then my information is by its nature 1 frame late, right?
No. It's unknown.
entries[x].
FPS can be crazy like 1000 times per second, where as physics is ~50 by default
Update is tied to FPS
I mean script execution order
not sure what ur doing there tho @dusky dune
Then it'll run in the same frame
oncollision gets called after fixed update
so if I set isGrounded in OnCollisionEnter, then the information in fixedupdate is old, right?
No, I lied
You're right 100%
correct. though ideally you wouldn't be relying on collision messages for ground checks
so I need to instantiate ui text in the game ive done that but I now need to fill each text box with a unique description I have the description in a JSON file and I need to read each description one text box and then move on the other other text box and read the description in. Make sense?
I see. So is there a way for me to generate collision data to use that same frame?
got this error
use a physics query for ground checks like a raycast or overlapsphere or something
surely you know that you need to access whatever field is on your Input_Entry class that holds a string . . .
or is this actually the #💻┃code-beginner channel
but its all saved to a json file and I can read it but dont know how to read each one into the ui text panel
public class Add_Clues_To_NoteBook : MonoBehaviour
{
[SerializeField]
private string FileName;
[SerializeField]
private GameObject ui_Text_Panel;
[SerializeField]
float ShiftClueText;
// Start is called before the first frame update
void Start()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.X))
{
AddCluesToNoteBook();
}
}
void AddCluesToNoteBook()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
for (int x = 0; x< entries.Count; x++)
{
TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
//Sets the text.
theText.text = entries[x];
}
}
}
is what ive done so far
this x< fucking spacing is irking me
way to show you didn't bother even reading what i said
I did read it maybe I didnt understand
clearly not. what field on your Input_Entry class has the string you want
Clue_Description is the name of the field
great! so you need to assign that string to the text property of your TMP_Text object
also keep in mind that you'll only see the last entry in the list with how your current code is set up because you instantiate a single object and just reassign its text property every iteration of your loop
why cant I use json file to read it in?
what?
soz I mis typed
that still doesn't make any sense in the context of the code. you've already deserialized your json at this point. you've got your List<Input_Entry> that you are iterating over. access the Clue_Description field/property inside that loop to assign to the text object
oh right now I understand better thank u
follow-up question: If I use GetContacts, would my information still be a frame late?
or would it be from that current frame
I am getting an index out of range error even though the for loop is <= why is this couldnt find much on google
void AddCluesToNoteBook()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
for (int x = 0; x <= entries.Count; x++)
{
Debug.Log(entries.Count);
//Sets the text.
theText.text = entries[x].ToString();
}
}
as you can see the count is 4 but the index is 5
why is it going one over ?
because when it reaches entries.Count it is still allowed to proceed depsite .Count being 1 more than the final index
you want it to be less than entries.Count, not less than or equal to
entries[x].ToString() this is also wrong
and you are still assigning the text of just a single object so only the last entry will be visible
when I removed the .ToString() I kept getting Input_Entry instead
yes and i already told you how to fix that. you clearly ignored it
why is instantiate not in the loop
if u want multiple ones
yh im realising this now it prints the same thin g
it only instantiates one text panel at a time when the user collects an item
put them in a list then
I mean it works now as intended
void AddCluesToNoteBook()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
for (int x = 0; x < entries.Count; x++)
{
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
Debug.Log(entries.Count);
Debug.Log(x);
//Sets the text.
theText.text = entries[x].ToString();
}
}
does using the toString really harm it?
it very likely doesn't do what you think it is
oh wait nvm
literally all you needed to do was access the public Clue_Description field on the object rather than call ToString on it
well, if it had a method called GiveMeSomethingThatIsntTheClueDescription(), i don't think you'd want to be calling it
so this
void AddCluesToNoteBook()
{
var entries = File_Handler.Read_From_JSON<Input_Entry>(FileName);
for (int x = 0; x < entries.Count; x++)
{
Transform parent = GameObject.FindGameObjectWithTag("Left_Page_Panel").transform;
GameObject new_UI_Text_Panel = Instantiate(ui_Text_Panel, parent);
TMP_Text theText = new_UI_Text_Panel.transform.GetComponent<TMP_Text>();
Debug.Log(entries.Count);
Debug.Log(x);
//Sets the text.
theText.text = Input_Entry.Clue_Description[x];
}
}
ohh textpanel isnt the textbox ur talking about ?
bro what the fuck
do you not know how to use c#? because if not, you should really consider doing some basic courses instead of just guessing
I do ive used it in the past
then what about Input_Entry.Clue_Description[x] do you think is correct?
well I need to get the x index of input_Entry no?
that sentence makes very little sense
x is a variable used to index your entries list
it has nothing at all to do with the Input_Entry class other than the fact that entries is a list of Input_Entry
if you can't see the problem here, you have a severe misunderstanding of how variables work, in general
theText.text = entries[x].ToString();
explain to me what this line does
it sets the theText text component equal to the x index of entries list and converts it to a string
that was my reasoning
close, but your ordering is weird
It gets the xth element of entries and calls ToString on that
then it sets the text field on theText equal to whatever the result is
now
theText.text = Input_Entry.Clue_Description[x];
where did entries go?
man those underscores makes evertyhing a chore to read..
they do, yes
i feel like this person doesn't even have a configured IDE considering the monstrosity of that line
that should be emitting a large pile of errors, yes
OK but this is #archived-code-general , its not quite beginner, but it isn't advanced either.
although i guess technically it would be valid if Clue_Description was made static for whatever reason. since you can index a string. still wouldn't do anything close to what they want to do though
it should be in beginner lol
oh yeah, that's most of the way to compiling
Perhaps based on the question, not the naming conventions.
yeah and with #archived-code-general you would at least expect someone to know how to access an array and use the . operator to access public members of an object
yeah for sure thats what I meant
well isnt entries a variable of type Input_entry ?
who cares? where did entries go?
why did you get rid of entries?
i am trying to grasp how you're making this error so you can fix that misunderstanding
well I would only use it once to load the list in why would I constantly load it in with each loop?
where are you "loading the list in"?
there are beginner c# courses pinned in #💻┃code-beginner
they cover how to use a for loop to access the individual elements of a collection. start there.
well, let me get ahead of you there and say that this is...not a thing
you have a severe misunderstanding of how this works
not sure if im honest
for (int i = 0; i < 1000; ++i) {
Debug.Log(i);
}
This just counts from 0 to 1000 and logs the numbers
yes I know that
for (int i = 0; i < entries.Count; ++i) {
Debug.Log(i);
}
Okay, so what does this do?
loads the elements of the list and stops at the last index
look, i know this is 100% correct and is not invalid in any way. but i gotta be honest, i hate that you are using the prefix increment instead of postfix increment and i cannot explain why i hate it
Where is it "loading the elements of the list"?
i switched a year or two ago and now i'm stuck doing it this way 😉
compiler?
once seen you cant unsee it
here, let me rephrase it
int num = entries.Count;
for (int i = 0; i < num; ++i) {
Debug.Log(i);
}
entries appears nowhere in this for loop at all.
right but you reference it with num?
but wouldnt the number of num be equivalent of the entries length?
Yes.
Suppose entries contained 1000 elements. This code would do exactly the same thing as the first block I posted
It would not "load the array elements" through some ill-defined mechanism
It just counts from 0 to 1000 and stops
That's it.
Now.
so far im with u
for (int i = 0; i < entries.Count; ++i) {
Debug.Log(entries[i]);
}
what does this log?
the index right?
Do collider contacts only get updated in the internal physics update? I’m having trouble finding info
yes
collisions are physics so it makes sense
the firsrt element of the entries list
I would say zeroth, but it's certainly the "first" one, yeah
thanks indexing
So, entries[0] is not an index
again, you should really just use a physics query for ground checks. then you won't have to rely on when collisions get updated. because you'd just be querying the current state of the physics scene
It's an element of the list
so, what does this log?
oh yh
ok I get u with that
would log the elements
Right.
by going through each index of th elist
So, coming back to this code
theText.text = Input_Entry.Clue_Description[x];
This is trying to use something named Input_Entry
It's trying to get a member named Clue_Description from it
Then it's trying to get the xth thing from Clue_Description
notice how entries is nowhere to be found
so we ain't getting elements from a list, for sure
right I get u now I think what confusing me is because the variable entries has the list Input_entry and the input entry class has the clue_description
entries is a List<Input_Entry>
Therefore, entries[x] is an Input_Entry
writing Input_Entry.Clue_Description is wrong. You need a specific Input_Entry to get the clue description from.
hello , i am tring to create a serilizable class that has a setup window
[Serializable]
public class WKArgsFloating<T, U> : WKArgsBase where T : WKArgsWindow<U> where U : WKArgsBase
{
public void ShowWindow()
{
T window = ScriptableObject.CreateInstance<T>();
window.args = this as U;
window.Init();
}
}
public abstract class WKArgsWindow<T> : EditorWindow where T : WKArgsBase
{
public T args;
public static Vector2 size;
public abstract void Init();
private void LostFocus() => Close();
}
i got this so far, is there a simple way to do that?
you're asking the concept of an Input_Entry to give you a Clue_Description
entries is a List<Input_Entry>, so entries[x] is an Input_Entry, so entries[x].Clue_Description is a string
(because, I presume, your definition for Input_Entry includes something like public string Clue_Description;)
right I get you entries has access to the input_Entry.ClueDescription and I should use that as it is a list of that class
thx for dumbing it down
Yep. You want to think about the types.
I have a List<Foo>, so I can get a Foo by indexing it
Foo has a string field, so I can get a string by accessing that field
For Cancelation Tokens do I just need to check if IsCancellationRequested is true whenever there is a loop? I'm thinking I'll supply it and set it to true when exiting play mode so the task stops. I don't want to use the Job system because It won't let me use managed objects which is a big inconvinience for me for this specific task...
Hey I'll this isn't made for asking for scripts but does anyone have time to teach me how to make a 2d character move
probably not but there are thousands of tutorials on that subject.
That's so extremely specific to your game that it isn't viable.
Left right and jump
You want a platformer tutorial then!
you might be surprised to hear that your description is nowhere near a complete description of a character controller
Generally yes, it just notifies that your task has been cancelled and you’d need to implement how to terminate the task
I just started
ok, just wasn't sure how to use the cancelation token
Generally if you don’t need cleanup you can just return or throw when it is cancelled
I am having trouble fetching my assets, yes I am logged in, yes I logged in and out.
server down rn
I think that's an ongoing problem with the servers
at least in ur region it seems
wrong text channel
Ok whewf, I am happy its not a me problem
I asked around for where to post this and they recommended here @glacial cliff ...
who did
you said Bugs
theoretically 400 is a client side issue, but it's possible they have some misconfiguration on their sever causing it anyway
i assumed coding bugs sorry
Can you access the Unity asset store?
thats not a coding bug lol
400 is a "Bad Request" in HTTP error codes, so it could be either side. Likely the client is requesting the wrong address, however that's still technically a Unity issue as a user isn't changing that.
that's... exactly waht I said haha.
try a vpn 🤷
what region are u in? its working in US
New Zealand
but either way a Unity issue >_>
Seems the chat has turned it into a #archived-code-general topic so..
Huh? Seems more like Unity-Support since it's not code related, other than the error code
yea I don't think I'll need cleanup. So basically just something like this pseudocode?
TaskLoop() {
while(working) {
if(token.IsCancellationRequested)
return;
// do work
}
}
static class CancelTasksOnQuit {
private static CancellationTokenSource onQuitTokenSource;
public static CancellationToken CancelToken => onQuitTokenSource.Token;
static CancelTasksOnQuit {
(application quit event) += OnQuit;
#if editor (player stop event) += OnQuit;
}
private OnQuit() {
CancellationTokenSource.Cancel();
}
}
StartTask() {
Task.Run(() => new TaskClass(CancelTasksOnQuit.CancelToken).TaskLoop());
}
thats on me for redirecting in the wrong channel thinking Bugs meant code 
Yes but then everybody starts deciphering error 400, making the post relevant
Right, we're still trying to help since this discord doesn't appear to actually have a general support channel (unless you can see one).
Not complaining or anything, just thought it was funny that the post became relevant. Also your right, there is no #unity-bugs.. bit odd?
Oh well, the moderator has spoken, all support questions now go to #💻┃unity-talk
I'm not going to argue xD
"Non-programming Unity topics & questions not covered by specific channels."
"I started a new project and got 300 errors, here is detailed information that I'm just going to dump in the general discussion area"
really...
I wouldn't bother arguing, just go with it
Make a thread if you are worried about it
I mean... that IS a lot of the questions there (minus the detailed information of course)
Just a screenshot of a ton of errors and "how to fix!?"
Yeah, I just wouldn't argue about it. You're not going to win here.
Didn't know people could get this triggered about a simple question in the wrong channel
you get tired of it after a while.
so, seemingly randomly, my scenes shadows started looking super dark and I have no clue what I did or how to fix it. Any suggestions? I am using the Built In Render Pipeline
Just a light baking issue most likely #archived-lighting
un related but really cool design
that looks nice did you make thoose houses
it uses free unity store assets. Using them as temp props for the time being
not bad but I rather do my 3d models on my own on blender but still looks great
yeah, I want to get there eventually but this is my first 3d project so its rough. Wanted to get game mechanics done before 3d art
I'm trying to use blender aswell
its quite awesome albedo only material can do something like this lol
i can tell theres not much texture used lol
with scriptableobjects, i'm trying to reference a gameobject prefab (from resources folder), but when i instantiate the scriptableobject, the gameobject variable is empty
it's still set in the scriptableobject asset, just not the instantiated one
anyone know what's going on?
I can't seem to find the answer online... my suspicion is no.
Can I invoke an event/delegate from a worker thread on the main thread? i.e. if I pass a System.Action into a task, then have the task call action.Invoke(), it will invoke it on the task thread, right?
If this indeed doesn't work, is there some way I can notify the main thread that the task is finished?
Delegate is just function call. It does not do anything special. You should look into UniTask for easy way to do this
I would prefer to stay away from libraries and such D: So is the only answer to have some sort of loop checking when it is finished?
Well look into that library since it is open source
Threading is not easy topic
Seems completely isolated or rather decoupled from Unity, try the c# server.
If I have two virtual cameras and I want to convert the player's mouse screen pos to the world pos of the secondary vcam at the time, how can I accomplish this?
because a virtual camera doesn't have the method of ScreenToWorldPoint(). So I'm only stuck with using ScreenToWorldPos for the main camera which ruins my game functionality.
true. I tend to ask here since c# server used to be dead. I'll give it a go though.
so I want the secondary camera to be for the game functionality and the main one to display the game but with another angle
This is highly convienient though
lol
Desperate Fight with a NRE
Any tips on finding the offending game object for renamed/moved scripts? I did some refactoring and this error message is unhelpful (even in 2022.3.7f1). When will this be more useful, unity? >:|
double clicking it doesn't bring me to the GO, and i don't see a stack trace
You can use something like descibed on this page https://gigadrillgames.com/2020/03/19/finding-missing-scripts-in-unity/
Hm, so recursively crawl everything in the scene looking for valid components (ie, counting them, iterating "known" ones, then spitting out the name/path of the GO when it misses). Nice trick.. Not sure it'll work for my use case though since I'm seeing that error on awakes/scene transitions.. but I might be able to adapt this a bit.
Thanks 👍
I probably ought to have saved my project before clicking something that's going to recurse through the entire hierarchy 😛
Works great though. Thanks!
im making a list of every upgrade (scriptable object) in my game
should this list be static or non-static?
would a static list cost more memory
Do you need it static? Also how do you plan to populate the list
public static List<WeaponUpgradeBase> possibleUpgrades { get; set; } = new List<WeaponUpgradeBase>();
private static bool possibleUpgradesInitialized=false;
private void Awake()
{
if (!possibleUpgradesInitialized)
{
possibleUpgradesInitialized = true;
//add possible upgrades from resources
}
}
like this
i don't need it static but i dont want to load it again every time i switch scenes
I dont see how switching scenes is related, you could place it inside DDOL as a way to keep it across scenes
probably would be better to make it a SO in its own right and have objects that need it take the SO as a serialized field. Doesn't make sense to have a list of upgrades exist in the scene, and imo your code snippet is very smelly
what do you mean by smelly
thanks for the help by the way
public, static, mutable list. Init flag. Has an awake, so now you can have execution order issues if anything else accesses that list in their own awake
the comment suggests it scans from resources folder instead of just having those items assigned
thanks for clarifying
im now sure this was a bad idea
ill use scriptable object for that
Hi everyone, I need help with an issue. I am making a Stardew Valley - type of game and I am working on an inventory system. Now, I have never build such a system, but I decided to model the inventory by an array of InventoryItems. I create an array on Start, but when I try to read through it, I get a NullReference error. Then, when highlighting the player GameObject in the inspctor (which holds the InventoryManager script) and I try reading from the array, the error goes away and it works perfectly fine. To me, it looks like the array is only created when selecting the script in the inspector. I don't want to link all the code here, If you know how to help me and need some of the code just ask for it please. Thanks
just link the code, and show the error
a null ref error is the same thing every time. its just a matter of debugging whats null and why
here is the code on pastebin: https://pastebin.com/jxVkRQ27
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.
this is the error btw
did you change anything from the script before sending? 120 is just an empty line, so i assume its 121
you can step through with the debugger to see what part is specifically null
I assume its the list[i] part because i dont see where you initialize those classes inside the list
i edited the message, i meant list[i]
oh
this are the logs if you add a debug.log(i) just above the error line
I start the game with nothing highlighted, and after the error I highlight the player gameobject from the hierarchy
and it just works
are you doing this all in 1 consecutive run? you should have error pause on because nothing should really run after this error
this also doesnt really change that list[i] can be empty considering some of your code does
Inventory = new InventoryItem[slotsCount];
then immediately searches on it
I don't have error pause on
I didn't even know it existed unitil now
so how should I create the array?
the array is fine, but the items inside the array havent been created
should it be like a loop and use Inventory[i].item = new InventoryItem() ? or something like this ?
you should debug to see what part is specifically null, maybe itll be more clear then
like use the debugger or just check list, then list[i] and list[i].item
Depends. More context would be needed.
Should you be creating new instances or referencing already existing instances.
i'll try and come back
I understand now
so the array is created and assigned, but each individual object in the array is null, so I can't reference any array[i].item
I added Debug.Log(list[i] == null and it returned true
but how does highlighting something in the editor changed that ?
it shouldnt really, I just assume you have the function calling from different origins but its hard to really say without more knowledge.
Regardless, you just have to fill in the array with valid entries of InventoryItem
I changed it to this: ```Inventory = new InventoryItem[slotsCount];
for (int i = 0; i < slotsCount; i++)
{
Inventory[i] = new InventoryItem(null, 0);
}```
and it worked
but I will try and find out if there is a more performant way of doing this
🤷♂️ that is your way of doing it, you're gonna have to new them all up anyways
actually what you could do is just check if item[i] is null, meaning no entry was ever put in that slot and then create it if its null. But this really just delays the inevitable of newing up an InventoryItem
this runs in start, so I should never be null in Update
but I assume doing it once this way isn't that bad
Id put that new Inventory thing in Awake but yea itd be fine still.
Unless you're inventory is literally 1 million size, you'll not notice any lag. And at that point, memory is more an issue instead of performance
you guys got any methods to make good random map generation
i was thinking of having premade rooms and just using spawnpoints like blackthronpods video just changing it up a bit
In my android build when I take a screenshot of my screen I get the problem that the rendertexture that I use for my map gets black. When I dont take the screenshot the rendertexture of the map works. fine.
Hey, how can I fix this?
I'm steering a missile, but it is oversteering because it's applying too much correction.
Limiting correction by 50% or limiting it over distance to the steeringPoint doesn't fix the oversteering. It's less, but the oversteering still accumulates over time and also the turn rate is affected.
The angular velocity of the missile is linearly interpolated.
// direction to the current steeringPoint
Vector3 direction = guidanceSystem.missileTransform.position - steeringPoint;
// calculating angles to steeringPoint.
float verticalAngle = Vector3.Angle(direction, guidanceSystem.missileTransform.up)-90;
float horizontalAngle = Vector3.Angle(direction, guidanceSystem.missileTransform.right)-90;
// This keeps error in range of turn rate
horizontalAngle = Mathf.Clamp(horizontalAngle, -guidanceSystem.yawSpeed, guidanceSystem.yawSpeed);
verticalAngle = Mathf.Clamp(verticalAngle, -guidanceSystem.pitchSpeed, guidanceSystem.pitchSpeed);
// setting how much correction to apply in each direction
float verticalError = verticalAngle / guidanceSystem.pitchSpeed;
float horizontalError = horizontalAngle / guidanceSystem.yawSpeed;
Vector3 correction = new Vector3(verticalError, horizontalError, 0);
guidanceSystem.SetGuidance(correction)
In the image the green line is the route for the missile and the pink line is for where the missile travelled.
You can see how the oversteering accumulates over time
Im making a game and its working fine when i play from the editor but after dying and reloading the scene it does something different (not work), theres no errors and some things work but a lot doesn't, what are the differences between the initial play and scene load?
There should be no differences. Are you using DontDestroyOnLoad at any point?
Or maybe static variables? Pretty sure they don't get wiped as well
dont think so although my events are which might be why
can you make non-static events?
Yes, but there's no need. Just clear them when the scene is loaded (in Awake, or if you have multiple instances of that script, then from another script that has only one instance and its job is to clean that event list)
It very likely is the problem, happened to me many times
alright, thanks ill try that
If I have call structure like:
Update() -> A -> B -> C -> D and I want to try to turn D to use threads and UniTask with async / await...
does it mean I also have to change A B C to async as well?
Can Update even by async?

I have a headache even thinking about it... I've moved my FastNoise generation from one place to to during terrain mesh generation so that I don't have to store it in memory and now the game is all jittery and I'm trying to put it in background somehow because all FastNoise calls take like 100ms and fps drops during that time
do update, a, b and c need to wait on D ?
yes because when handling input I have calls like "GetBlockType" which use this FastNoise script internally
But maybe it was a mistake to move it. Before I stored all cube values in 3D mesh. But I figured I don't need to store the noise generated values if I can generate them anyway on the fly. But it turns it's slow to generate them on the fly 
This FastNoise script makes some fractal calls and crazy math loops which I don't understand which take some time
Do you need it to be done more than once ?
At the moment yes, each element in my 3D block array results in this noise script call
OK
Sorry for the off topic, but is 150 TB read/write a lot for a 256 GB ssd?
I'm asking, because my pc won't boot for an hour or so due to disk check.
Is there any way to have an event which fires whenever a pointer is pressed anywhere?
Do you mean a mouse click?
Yeah, but also a touch for instance.
Are you using a new input system or an old one?
the new one.
@proven path
I see, I would want soemthing like the second one, but not bound to an object like in the example.
Bind it to an object. Namely an invisible UI Image on a Screen Space - Camera canvas with a plane distance of 1000
Unverified AI responses are banned in this discord BTW
Sorry
That sounds convenient, I guess I will go with that then.
Thanks you guys!
{
var mousePosition = Input.mousePosition;
var ray = Camera.main.ScreenPointToRay(mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Check if that is your object, but then you will need a collider.
this is much better
}
}```
i am using this kind of logic everywhere. it is more simple than distance of 1000 of canvas @proven path
!eventSystem.IsPointerOverGameObject() this part is just checking if mouse is over gameobject not a ui elemet
I disagree that this is more simple at all
My issue with that is, that I would need to call this in an update method, while I am searching for an event based approach. Still thanks though.
If I use UniTask do I need to use UniTask.Create() or can I just write await SomeAsyncFunction() ? if it is public UniTask async SomeAsyncFunction(){}
I'm having some strangest bug where my code won't even run or throw any errors anymore and I don't see what's going on
You can run UniTask either in an async or in another UniTask method.
private async void Start()
{
var myString = await MyTaskReturnString();
}
private async UniTask<string> MyTaskReturnString()
{
UniTask.Delay(TimeSpan.FromSeconds(1));
return "TaskCompleted";
}
if i wanted to disable the gravity and add my own, what the code would be like?
void FixedUpdate() {
rb.AddForce(gravityVector, ForceMode.Acceleration);
}```
i now understand why my vehicle kept sliding from mountains/slopes/etc. it was gravity
kinda obvious but somehow it escaped me
Hey,
How to get an angle in a 180deg range to a object?
This only returns an angle in 90deg range, and also works in reverse?
Vector3 direction = target.position - antenna.position;
float verticalAngle = Vector3.Angle(direction, antenna.up)-90;
float horizontalAngle = Vector3.Angle(direction, antenna.right)-90;
You may want SignedAngle
oh, I see
I thought you were trying to get angles in the range [-180, 180]
I did something really similar a few days ago. Getting the pitch and yaw components takes a little more work.
How would I get it to work like this:
forwards = 90
left = -180
back = -90
right = 180
In both vertical and horizontal
would a yaw value (rotation around the up axis) and a pitch value (rotation up or down from horizontal) work?
Vector3 flattened = Vector3.ProjectOnPlane(entity.transform.forward, Vector3.up);
yaw = Vector3.SignedAngle(Vector3.forward, flattened, Vector3.up);
Vector3 rotated = Quaternion.AngleAxis(-yaw, Vector3.up) * entity.transform.forward;
pitch = Vector3.SignedAngle(Vector3.forward, rotated, Vector3.right);
Here's how I did that in my game.
It first squashes the direction into the XZ plane (removing the vertical part) and computes a signed angle
Then it undoes that rotation to give you a vector that points up or down, straight ahead
And then it computes another angle.
Can this be used to calculate an angle to an object?
Like Line Of Sight
No, I did this because I needed to know the yaw and pitch to set up the player input correctly
(so that taking control of an entity doesn't make it spin to 0 yaw and 0 pitch)
Are you trying to calculate line of sight for an antenna on a planet's surface?
if you want LOS, you usually just use a raycast
I'm precomputing what targets I need to raycast
I'll exclude targets that are out the radar antenna's range and fov
then raycast to query wheater the target is blocked by terrain
Vector3 direction = target.position - antenna.position;
float range = Vector3.Distance(target.position, antenna.position);
float verticalAngle = Vector3.Angle(direction, antenna.up)-90;
float horizontalAngle = Vector3.Angle(direction, antenna.right)-90;
bool outOfCone =
verticalAngle < maxVerticalAngles.x ||
verticalAngle > maxVerticalAngles.y ||
horizontalAngle < maxHorizontalAngles.x ||
horizontalAngle > maxHorizontalAngles.y ||
range > maxRange;
Targets that are outOfCone are not raycast
Do you need separate horizontal and vertical components?
yes
okay, so you can just do one Vector3.Angle query
hm, so you need to separately figure out the dispersion on two different axes
That should look kinda similar to this, but simpler, actually
You need to use Vector3.ProjectOnPlane to throw out the vertical and horizontal parts of the direction vector, then do the Vector3.Angle calculation normally
Vector3.ProjectOnPlane(direction, antenna.right) would give you just the up-down part
Vector3.ProjectOnPlane(direction, antenna.up) would give you just the left-right part
ProjectOnPlane flattens the vector onto a plane with the specified normal vector
Then, compute Vector3.Angle(flattenedDir, antenna.forward) to get an angle.
you can imagine it removing the part of the vector that lines up with the normal vector
if the normal vector is +Y, the resulting vector will only have X and Z components
Okay thats new to me. Give me sec I'll try to implement this
It's super useful.
You might do something like this...
Vector3 something = whatever;
something.y = 0;
ProjectOnPlane can do the same thing, but in any axis
The opposite is Project. It returns only the part that aligns with the second vector.
(project-on-plane just subtracts the result of Project)
How can i show Non-Serializable struct (UnityEngine.ResourceManagement.ResourceProviders).**InstantiationParameters **in inspector? I searched and also tried PropertyDrawer but didnt work.
I have no idea why they did not marked this one as Serializable...
Looks like a class and not a struct https://docs.unity3d.com/Packages/com.unity.addressables@0.6/api/UnityEngine.ResourceManagement.ResourceProviders.InstantiationParameters.html
I'm assuming it's non serialized as well
I don't think a property drawer even comes into play if it's on something that isn't serializable
Yep
serialized properties and all that
The first thing that comes to mind is making your own version of that struct that is serializable
and just copying the values into it
a custom editor could probably do it
but custom editors are more of a nuisance
I can deal with it. I will try the Custom Editor
Youre right too
i don’t understand the issue
there is a struct that is defined and non-serializable? or you defined a struct and want it to be non-serializable?
Hey all, i need some advice, whats the best way to implement the syncing of data that isnt a Mono/NetworkBehavious class. Or do I do it in the class that is a network behaviour.In my case I have an Inventory system where the "physical" inventory classes are not monobehaviours. however the inventory is attached in a monobehavious class. So do I just call a serverRpc to update that inventory? within the networkbehaviour containg the inventory
void SyncInventoryServerRpc(Inventory inv){
inventory = inv
}
Anyone experience with creating screenshots for android? It destroys the renderTexture connection of my map gob?
or network variable
How do i use NavMesh.CalculatePath(...)? the func keeps returning false for my maze despite their sometimes being a path between the two points.
(I'm trying to build a spawn checker)
send script
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.
spawn points and exit points are simply a transform attached to a tile game object that is then passed into a wave function collapse generator. the script is attached to the parent spawn tile and calls at Start()
every tile is returning false tho
does SetDestination work on them
let me check
if its false, somehow its not a complete path
oh alr. well time to make it valid then
hmmm maybe it has to do with generation of the nav mesh grid
basically the tiles are assembled in the awake method
the nav mesh is built in the start method which is called second
so you call calculatepath before the nav is baked ?
that or i specifically write the code that calls the spawn point checks after the nav mesh build
okay yeah, putting the generation code in the awake method allowed the paths to execute as true.
same
The WF collapse generator also runs in the awake method and i was separating those concerns but they seem to both run fine in the awake method
but if i have to i guess i will use unitys order of events
have you seen this before
https://docs.unity3d.com/Manual/ExecutionOrder.html
hmm ive seen a more generalized version
How do I find out whether a point is to the right or to the left of a direction?
Im pretty sure default(customClass) is null, is it the same for default(Vec3Int)?
left and right are relative depending on your up axis. if you define a left vector and a right vector you can see which one a point is closer to
It's 2d
so you have a player position and a forward and you want to see if a point is left or right
Pretty smart actually, I was trying to use dot product but didn't succeed
Cross product*
you can use dot product
from stackoverflow:
float dot = a.x*-b.y + a.y*b.x;
if(dot > 0)
console.log("b on the right of a")
else if(dot < 0)
console.log("b on the left of a")
else
console.log("b parallel/antiparallel to a")
Are you sure it's dot product and not cross?
Or can both be used
Because I saw cross on the Internet
the default of any struct has all the fields set to zero/null so it would be equivalent to Vector3Int.zero
in 2d both cross and dot product can describe if vectors are in the same direction
https://www.geogebra.org/m/psMTGDgc
https://www.geogebra.org/m/Yu6869By
those are helpful for visualising
dot product is more in front of or behind, but if you use a vector 90 degrees form the one you want it works
ahh thanks
For some reason it won't let me set the position where the projectile spawns with the remote bomb ability
notice how spawn point says "Type Mismatch"
anyone know if it is possible to have c# create a wrapper for python scripts to be ran in unity. I wanna use this: https://github.com/Osmodium/PathfinderTextToSpeechMod
Then instead of using the windows commands (natural narrator is not supported in their library). I would use the google chrome.tts with edge or chrome to pass in the text to be read. It doesn't need chrome to be installed on windows, just on mac. But it should be able to cancel the audio and receive everything from a c# script
In short, I am looking for existing wrapper libraries that could accomplish this
Every object in a Scene has a Transform
You can't reference a transform from assets, like a scriptable object is.
damn, how am I gonna have projectile abilities then
im trying to make abilities flexable
You need to Instantiate it
also I know you can call chrome.tts in a c# script since its through the api. I am just thinking of using another github project to make it easier
yeah which requires a transform
scriptable objects can't be instantiated onto the scene (they don't inherit from monobehaviour) and as such also can't get a transform component
you have to make the scriptable object a field inside a monobehaviour class
scriptable objects are basically just instances of data
Just make a POCO c# class with a mobo wrapper.
[Serialized]
class Ability
{
string Name;
string Description;
...
public Ability(string name, string description, ...)
{
Name = name;
Description = description;
}
}
class AbilityWrapper : MonoBehaviour
{
[SerializedField] Ability ability;
void OnAbilityUsed()
{
ability.DoSomeStuff();
}
}
POCO?