#archived-code-general
1 messages ยท Page 28 of 1
Because packages can be updated, and it requires me to only use git flow to push updates. They also support dependencies, and are well isolated by default.
Meanwhile UnityPackages require extra work and have no features.
Or BoxCastAll in your case
thanks I think that's what I need
Since you want all the gameobjects in that box, not just a single one.
So I have a strange issue
For whatever reason, my enemy AI moves just fine in the player
But I built it and in the build version, the AI keeps starting and then stopping
I'll try building it again and see if there was just something wrong with that build
I also get these messages when trying to build
hi i have a problem at my passing system
when i press the button the ball goes to other player but it comes back.
and ball is goes to other player very fast
using System.Linq;
using UnityEngine;
public class Passing : MonoBehaviour
{
private Passing[] allOtherPlayers;
private Ball ball;
private float passForce = .7f;
private void Awake()
{
allOtherPlayers = FindObjectsOfType<Passing>().Where(t => t != this).ToArray();
ball = FindObjectOfType<Ball>();
}
private void Update()
{
if (GetComponent<Player>().isHaveBall)
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical);
Debug.DrawRay(transform.position, direction * 10f, Color.red);
var targetPlayer = FindPlayerInDirection(direction);
if (targetPlayer != null)
{
if (Input.GetButton("Fire1"))
{
if(targetPlayer.tag == this.gameObject.tag)
{
GetComponent<Player>().isHaveBall = false;
GetComponent<Player>().isControlling = false;
targetPlayer.GetComponent<Player>().isHaveBall = true;
targetPlayer.GetComponent<Player>().isControlling = true;
PassBallToPlayer(targetPlayer);
Debug.Log(targetPlayer.name);
}
}
}
}
}
private void PassBallToPlayer(Passing targetPlayer)
{
var direction = DirectionTo(targetPlayer);
if (direction != null)
{
Vector3 ballToPlayer = new Vector3(direction.x * passForce, 1.0f, direction.z * passForce);
ball.gameObject.GetComponent<Rigidbody>().velocity = ballToPlayer;
}
}
private Vector3 DirectionTo(Passing player)
{
return Vector3.Normalize(player.transform.position - ball.transform.position);
}
private Passing FindPlayerInDirection(Vector3 direction)
{
var closestAngle = allOtherPlayers
.OrderBy(t => Vector3.Angle(direction, DirectionTo(t)))
.FirstOrDefault();
return closestAngle;
// Non-LINQ Version
//Passing selectedPlayer = null;
//float angle = Mathf.Infinity;
//foreach(var player in allOtherPlayers)
//{
// var directionToPlayer = DirectionTo(player);
// Debug.DrawRay(transform.position, directionToPlayer, Color.blue);
// var playerAngle = Vector3.Angle(direction, directionToPlayer);
// if (playerAngle < angle)
// {
// selectedPlayer = player;
// angle = playerAngle;
// }
//}
//return selectedPlayer;
}
}```
idk where is the problem
and the other script
You should not run a GetComponent<> in the Update like that
hmm ok i will try after 5-10 min.
thanks
It probably won't solve your problem, but you shouldn't have it like that
You should cache the player
private Player player;
private void Awake()
{
player = GetComponenet<Player>();
}
And this as well
i did it
Can't help you with the problem. I can help you with your coding style, though.
- Like Wumpie said, don't have
GetComponent<Player>()in your code. Store it in memory when you callAwake. - Add guard clauses to your code, to avoid nesting. Instead of checking
if (GetComponent<Player>().isHaveBall), checkif (!GetComponent<Player>().isHaveBall)and add areturn;keyword. This makes your code much more readable. FindObjectOfTypeandFindObjectsOfTypeare bad for performance and generally a bad idea to use, as they can easily cause problems. Consider getting your components another way
Can I have a variable in a ScriptableObject be another script (not to a prefab) that is of a specific type? I have configuration ScriptableObject that defines how to create variations of a type and I want to define a script that should be added to the GameObject that I'll create at runtime.
eg, I could put a script name in the config ScriptableObject and then do something like:
gameObject.AddComponent(Type.GetType("ScriptName"));
But I'd like to avoid using strings and searching and instead directly pass the class/type reference.
There isn't a built-in way to do this, but it's trivial to make a custom serializable type that saves the name of the type as a string, but exposes it as a dropdown in the editor. For example:
https://github.com/SolidAlloy/ClassTypeReference-for-Unity
is there a unity library nuget package? I want to import in a netstandard2.0 class library to share certain types like vectors
No, you should create a Unity project and shape it to be a package
basically I just want to create models that are shared by client and server
I know, I also tried doing this, but there is no point in doing it like this
why not?
I made a multiplayer package and I also tried to do it outside of Unity, but Unity has too many limitations to do this
One simple thing I can think of right now is how Unity can't work with constructors, and how you can't use monobehaviours in general
I don't want mono behaviours
it goes to the other player, then it comes back
You might aswell make a blank .NET Standard 2.0/2.1 project without Unity
I just want model classes so that the API can communicate
Thanks that is exactly what I wanted. Even the inheritance validations. General question on using something like this that has an MIT License, I can pull that package in as a library and use it as is and then sell my final project, yeah? I've been hesitant to use other libraries because I don't want to misunderstand a license or what I may be required to do.
but I want certain types in those models
Try extracting UnityEngine.dll
There's no package that does this
I believe, since Unity compiled in .NET Standard 2.0, you can also extract your build DLLs from a build and reference those
If you make an asmdef folder specific for API stuff you would get it as a dll
it's what I'm doing rn
MIT license is one of the most permissive licenses. The only condition is that you include a copy of the license somewhere with your game. It can be just a text file in the build.
Probably still requires UnityEngine though
guys i fixed the problem 
well I can just rip some models
no harm there
actually it's gonna be a problem there are a fuckton of DLL's
can't import them all
when clicking on a UI input field, it automatically highlights all the text that was typed in and if you start typing, it will delete everything, is there a way to make sure the text isn't selected so that the user can just continue typing without all the text being deleted?
Yes, because dependencies
Usually Nuget or Unity's package manager handles this
Have fun ๐
this doesn't really make sense to do
what is your goal?
nuget for unity and other similar packages do not work very well
no, I mean I have a class library projects, I want to import the unity dll into it to steal the models
you can create a project using dotnet project with netstandard21 as the framework, add your package, then publish it. all the dependencies will be gathered for you. you will have conflicts with unity supplied dlls that you can resolve with ignore version verification. good luck
oh i see
yeah I figured I won't do it
I will just make my own Vector3, since it's the only model I wanted
you can also reference it directly on your system, which will work
So I have many layers. Terrain layers like water, desert, grass, etc. Object layers like trees, mountains, etc. Other layers like ChopTreesHere, MineHere, PowerLines, etc (not named those). I also support mods providing definitions and handlers for whatever layers they want to add, eg a Gas Pipe Layer.
Since my game is entirely procedurally generated, I'm not hand crafting anything in the editor. I'm also trying to avoid preconstructing these layers because I don't expect modders to preconstruct anything.
Currently I load all Configurations from Resources, cycle through each Config and build the layer as defined, which includes attaching the referenced handler to that layer.
Does that make sense?
do you have a screenshot handy?
of your game
can I use a Task to update gameobjects asynchronously?
lol, super early prototype but here. Currently working on Zoning layers which is where the layers start to actually become managed. I can draw previews but working on creating a ChopTrees zone that will be managed.
looks good
you can use tasks to more succinctly deal with time and player loops in unity, but you cannot use it to do work on game objects off the main thread
does the game have to be closed source?
are you sure there is any value in that?
is there an Invoke method?
to run code on the main thread
what are you trying to do?
hey some help
i see. you can use unitask to achieve this succinctly. it offers await UniTask.SwitchToMainThread(). tasks are not threads.
What do you mean? Other than the hope that I do eventually release the game and make some money from it?
async Task()
{
while (true)
{
await InvokeMainThread(()=>{ });
}
}
@polar marten
i'm making a rythm game and sometimes unity lags a little when loading and then the moving stuff are late and the music is sounding off
you can eliminate this cantankerous plugin architecture by simply open sourcing your game
then if people want to make changes they can pull request it to you in github. if they cannot practically use the github UI, they will not be making interesting mods to a simulator anyway
you can use the thing i said
take a look at unitask
it's a package?
yes
Oh I see, interesting thought. One counter argument to that is that modding gives players choice. Take the Rimworld community (a core inspiration for my game), there's the vanilla experience and then there's the modded experience. Some mods are loved by some and hated by others. The modding capabilities of games like Rimworld and Cities Skylines is the model I'm following.
you can always make it a checkbox
anyway, it's your call
Also, this plugin model feels right to me, but I'm guessing it's a anti-pattern in Unity
you are at the start of a long journey
the rimworld guy had been embedded in the game industry at the right place and the right time for a while before rimworld, and even then i'm sure he would architect it quite differently with the knowledge he has now
This feel right to me, no?
MapLayerConfig[] configs = Resources.LoadAll<MapLayerConfig>("");
foreach (MapLayerConfig config in configs) {
GameObject obj = new GameObject(config.name);
MapLayer mapLayer = config.AddComponentTo(obj);
mapLayer.transform.parent = transform;
mapLayer.Initialize(config, width, height);
mapLayers.Add(mapLayer);
}
Yeah, I'm not following their architecture at all. Having modded that game, I know a bit about their code base, but I'm not following their patterns (I don't agree with much of it). (Not bashing their code, it works really well and is easy to understand, and I absolutely love their game)
okay well i have shared my perspective.
it is a long journey to
and make some money from it
i am trying to say rimworld guy had already worked on many successful games, at a studio that actually later imploded, so serendipity had a big role
Yeah, and as someone with a fulltime job and a family, I temper my expectations already ๐
Still fun to work on and imagine an eventual end. For the moment, just a fun side project POC
is is bad for performance to get the transform of game objects without caching?
like, do I save a transform field or gameobject field?
are you using that for mods?
whichever you need more often
if not both
alight
It's actually rare that GameObject is the best type for a reference
usually you're more interested in some particular component on the GameObject
I see
Partly, and also it simplifies my process. I find it easier to create a new resource folder, drop in some textures, define a config, and let my existing code integrate it without needing to create a Tilemap in the editor and configure everything.
GameObject is only useful if you want to do something involving the active state of the object or its layer
i think a lot of this stuff ends up having a crazy ants architecture which is fine
personally i would try to implement as much of the game as possible myself, without any notion of plugins, and once it actually works, pluginify it
well, i'm just pretty sure it won't work for modding as the resources folder doesnt exist in builds. Think you'd need asset bundles or something like that, but i've not tried before
you will not have the wisdom for how to do plugins before a working game exists
Yeah, I thought of that. I don't really want modders to even have to create AssetBundles, but I figure this architecture gets me closer to that. Extending this to some other way like AssetBundles is something I'm assuming can be done. (leaving it as an assumption for now)
that is my polite way of saying that the architecture for plugins is bad
Noted, and I appreciate the discussion. I actually found that when I pluginified terrain, adding new terrain layers was so easy. I'm working on the first managed zone (chopping trees) and then I expect other zones (mining stone) to be easy. Attaching screenshots of my grass layer definition (no prefabs or game objects) (yes I'm sure I need to optimize sprite sheets or something like that).
it's really hard to say
I don't mind brutal honesty
lol
on the other hand, i think i have a hard time seeing a bigger picture here because i don't play rimworld
i played a lot of cities skylines, but then i stopped playing
i never tried modding it
i author an open source game, and it has an audience, and people make the pull requests the way i describe, but end users are authoring text assets
How do i change the y axis of the gameobject without affect the x or z axis
and i had an a-priori thesis for a moddable (community authored) game that would have an audience, that wouldn't really fit for a city builder
other than the game i made, it would make more sense for (1) a game about shoes, (2) a game about hotwheels/cars
be more specific about what you mean by "y axis"
and actually, boost.ng/rigs of rods is probably that cars game
my gameobject would be rotate around an cube, but i want to change the y axis only
could someone help me with a unity project i downloaded?
Red: Rotate around
Blue: Moving y axis.
I want to control what height (Y axis) would the gameobject be rotating.
I dont know if its a compatability issue or something, but for some reason specific sound effects dont play and some stats dont display properly
@tough osprey so basically what i am saying is
unless you have a very strong thesis for why this game would have a modding community... it's best to focus on a simpler architecture that lets you make a really good game. the thesis "popular games attract mods" is much simpler than, e.g., mine, "a bunch of specific stuff about card games that makes a community authored CCG popular as a consequence of it being moddable"
It's a program that was showcased around a year or so ago...and for some reason nothing is working to fix it so far
anyone have any ideas what might be the issue?
do you have a link to the project?
I was hoping to do what they said in the video and add custom voice lines and parameters
what version of unity are you trying to open the project with?
though, i look at the comments and more and more people are noting how it doesnt work
i dont have unity, i just open the exe
...i assume that might be a factor
well, i assumed it was more of a general issue
you can download unity 2020.3.25f1 and open the source here https://github.com/LowLevelLemmy/LLL_Mantis
This is a game that reads your browser history (locally), then roasts you. PLAY IT ALONE! - GitHub - LowLevelLemmy/LLL_Mantis: This is a game that reads your browser history (locally), then roasts ...
you are on the start of a long and fun journey
it sounds like you are at the very, very beginning of this journey
when a task is created in unity, is it always on a seperate thread or is there a chance it will be put on the main thread?
depends how you create the task
oh? I just do this
Task.Run will run on a separate thread
bump
sorry for the question but how i do for set somethings on dontdestroyonlaod because my game manager is in the level not in the main menu
and i want to set somethings on main menu
also don't crosspost
Is there a built in attribute that makes callback on Application quit?
I need some proper cleanup callback for statics
not an attribute, but there's a few events you could use
https://docs.unity3d.com/ScriptReference/Application.html
no mono for me
Allthough I have been using mono bridge
(hidden go)
kinda what I wanted to get rid of in the first place
๐
๐ค
it doesn't work in Editor
it seems
I'm having trouble with my player movement script. I've been using rigidbody.MovePosition, but I wanted to have collisions work so I switched to rigidbody.AddForce. However this causes my rotation to bug out. I'm using rigidbody.MoveRotation which worked perfectly fine until I switched to AddForce. Now the player will sometimes jitter in rotation.
Here is the new behavior.
missing from your description here is your actual code.
one sec
Previous behavior.
sd.velocity = Vector3.ClampMagnitude(sd.velocity + acceleration, c.maxVelocity * movementMultiplier);
rigidbody.MovePosition(sd.velocity * Time.fixedDeltaTime + transform.position);
Vector3 upDirection = sd.CalculateAverageUp(sd.attachmentDistance);
Debug.DrawLine(transform.position, transform.position + upDirection, Color.magenta);
Vector3 forward = Vector3.ProjectOnPlane(sd.camera.forward, upDirection);
Quaternion targetRotation = Quaternion.LookRotation(forward, upDirection);
rigidbody.MoveRotation(
targetRotation
);
This isn't enough context really
where is this running
Update? FixedUpdate?
what is sd?
It's a method called by fixed update.
it's hard to make a rigidbody player controller that works. try kinematic player controller. it is a free and high quality asset
i believe it supports this style of movement that you are going for
rigidbody.MovePosition(sd.velocity * Time.fixedDeltaTime + transform.position);
shouldn't this be
rigidbody.MovePosition(sd.velocity * Time.fixedDeltaTime + rigidbody.position);?
plus I thought you said you switched to AddForce
ah yes, I accidentally left that part off.
rigidbody.AddForce(acceleration);
this would be instead of the first two lines of the previous.
If you're doing BOTH AddForce AND MovePosition that'll be somewhat problematic.
No, I'm not doing both. I comment out the one I'm not using.
If it's more clear I can do a pastebin
what is the difference between transform.position and rigidbody.position, when the rigidbody is on the same object?
they can be different especially in between physics updates, as the Transform may be interpolated for visual smoothness
I'll try that instead.
Actually that's relevant to the previous way I was doing it so nvm
i think you are on the right track, but also on some hard tracks
like tracks that will make it harder to achieve what you want
ok, so advice?
so when you do something like this
[HideInInspector] public ClingState clingState;
[HideInInspector] public FallState fallState;
[HideInInspector] public JumpState jumpState;
this is telling you you are making something that is tightly coupled
like you can pretend to decouple something by making a class hierarchy and a state machine or whatever
public InputActionReference move;
public InputActionReference sprint;
public InputActionReference jump;
but stuff like this is telling you, well it's strongly coupled
you can't make a strongly coupled thing like movement, particularly idiosyncratic spider wall clinging movement, and turn it into something decoupled
you can pretend it is decoupled
but you can't make it decoupled
am i making sense?
Yeah.
it helps you organize stuff intellectually and emotionally to have these separate scripts
i'm not saying it's bad
but it does get in the way
Yeah my purpose was mostly organizational.
but I wanted to have collisions work
going to your original question, you mean collisions in the sense of confining the character movement naturalistically. like the spider cannot move through walls.
right?
or do you mean the spider should interact physically with something like a swinging pendulum - it would get knocked back by a conventional unity physics object
so what I have right now will keep the player from going through walls only to a point. Once it is going fast enough, like when I press sprint, then it will clip right through.
So yeah, the first one about going through walls.
okay
can i step back one more time?
i think it is valuable to try to author this yourself for education purposes and to make innovative movement
and we'll talk about the techniques to scale up to support innovative movement
unfortunately, it involves, for the most part, reinventing the https://docs.unity3d.com/ScriptReference/CharacterController.html for your specific needs
it's about understanding how this works
it's worth looking at this asset
@scenic creek i'm going to go ahead and fork my default multiplayer sample here - https://github.com/appmana/appmana-unity-starter-hdrp - and import this asset
Hello all, Does anyone know how to select an AR object using Unity AR foundation and then an AR text panel appears? the panel also needs to dissapear after i click on the AR object again. I tried looking for tutorials online but there isn't really anything on this. I only started coding so im slightly struggling on this
you're on the start of a long journey
would specific tutorials be helpful? what is an example of something you want to make
i want to create a info button object, when selected using raycast, an text panel appears with instructions
An Ar object is like a regular object. You would raycast from the screen position of the tap into the scene, detect a hit and do what ever you like after that. So you should start with how a tutorial on how to fire a raycast from touch input and detect a object
then when im done reading, i can make it dissapear by selecting the info button again
I'll look into using the kinematic controller. I didn't think anything that was prebuilt would work for what I'm doing since it's pretty different movement from a lot of games, but I'll see.
As for the moment, is there any way to fix my jittering issue with a quick fix?
@scenic creek so based on the KCC source, you will be reimplementing, using raycasts, a character controller
Why is OnMouseEnter() or OnMouseExit() not being called?
So is there any way I can fix my current jittering issue without rewriting my entire game?
does your object have a collider?
Also are you using the new input system or the old one
Yes, it's instantiated in the code
I didn't install any packages. I'm using whatever input system that comes with 2021.3.16f1
should work as long as nothing is blocking it and your mouse is actually over the collider
what kind of object is this
is it in the game world, or is it UI?
It's in the scene, not UI
hey there, how can i make bool true after one press of a button and after another set it to false (like a switch)
myBool = !myBool
thanks
hard to say without reading all of your source and trying it myself. i think you have to do this one on your own
I think the only part that should be relevant is the part I posted. That entirely controls the movement and rotation in those lines.
How would I get a position of a collision ?
I have a bomb that can be dropped and I'm trying to create an explosion at the impact point
how would I achieve this ?
you're using the UnityEditor namespace in code that isn't editor-only
(second error)
Got it, that fixed everything, thank you
how can I get the angle required to face another Vector3 from a Vector3
to - from``` will give you the direction vector.
An "angle required to face" is quite a vague concept.
You'd have to define that better, like "The number of degrees around <some particular axis> required to rotate from the current heeading to a heading facing the target"
OnCollisionEnter should give that information
If you have a conditional shader that you want to be able to turn on and off, do you fold that into your normal shader and have a bool for it, or do you make a second shader and add it as another material on top of the normal one when you need it?
Er, no, apparently you can't use bools to control shaders. You have to swap between materials or add new materials
just to be on the same page
I think this involves converting 2D rectangle to a 3D box by raycasting each corner of the rectangle?
or is there a built in method that lets me convert a 2D rectangle on screen to a 3D box on the ground ?
I realized if I raycast corners and convert to a box it would require also scaling the box to be bigger/smaller when it's further/closer to the camera which adds a lot more complexity that I dont know how to calculate accurately
It depends on your game. If you have an orthographic RTS camera like AOE2 then you wont need to. If you have a perspective camera, there are instances you need to do what you say. If you would just look down on the map perpendicular, you could also skip that. If you have a perspective camera at an angle, it might be more useful to draw an invisible cube that represents your selection box, that has the vertices changed so that the box starts small and gets bigger at the end.
mine is a perspective camera at an angle
So I should maybe do a cube that looks like this...?
https://youtu.be/OL1QgwaDsqo?t=681
I think you want something like this. Maybe follow that tutorial.
Yeah exactly.
thanks I was looking for videos but didnt find what I needed
Well if this is what you wanted, then BoxCast isn't the way to go. This isn't a box anymore ๐
yea it's warped...
More like a pyramid.
probably
that gave me an idea
but video first
initial idea is to have a pyramid box collider
but will see the video first
Well the pyramid is warped too, that's the fun thing about perspective
yea...
Any advice to start learning coding for vr
learn regular Unity first
then throw in VR stuff when you're comfortable with the basics
Alr done
then take a few VR tutorials to learn the basics of VR
I feel uncomfortable when he uses the same name for a local variable and a class-scope variable
i went back 5 times to make sure i'm not insane, it was confusing
Well the idea is good, not saying the execution was fully correct ๐
But I have seen this style in other videos too
also he casually made this array int[] triangles = { 0, 1, 2, 2, 1, 3, 4, 6, 0, 0, 6, 2, 6, 7, 2, 2, 7, 3, 7, 5, 3, 3, 5, 1, 5, 0, 1, 1, 4, 0, 4, 5, 6, 6, 5, 7 };
without saying why it is like that
That's just the first one that came to mind. Also, there are a bunch of examples on stackoverflow
Well he sort of explained that part with the box before he wrote that
yes sorta
0, 1, 2 = a triangle, 2, 1, 3 also, 4, 6, 0 too etc
now i get the pattern in the array
Is there still a part you don't get?
he added vector2 + vector3 * float
which is fine for him but an ambiguous operator for me
does something the supports the .net standard 2.0 imply that is also is compatible with the .net framework or no?
Can you show your code?
is your goal to create a frustum-style selection box for RTSes?
But corners is a vector3 array?
okay. unfortunately doing this in a general way is pretty complicated. you can try this package: https://github.com/pointcache/UnityFrustum
hmmm I messed up then Ill back track
this is authored by someone on this very discord
Thanks for the suggestion
i know you said pyramid, but the reason this maybe has been a struggle is because the shape you are looking for is a frustum
would abstraction be helpful in unity
right
anyone know how to use ImmutableDictionary/List/Array in unity? when i try to use it, i get "unable to access internal class" even though i have using System.Collections.Immutable; at the top
immutablelist is not available in .net standard 2.1
what is your objective? .net standard 2.1 is newer than .net framework 4, and it is roughly a subset of .net framework 4's core libraries
they are strictly not compatible, but usually they are
ahh bummer
Does Scroll Rect move based on moving mouse while clicking (dragging), mouse scroll, or both?
I didn't try it in code yet but in unity it looks to be working
Thank you
and thank you for the big boost
https://ctrlv.tv/WQqe
Hello,
why is this happening to me? It works for me going forward, but once it has a negative vector, it stalls.
{
Vector3 lDirection = this.m_Direction == EscalatorDirection.Forward ? this.transform.forward : -this.transform.forward;
if (Is.All(collision.collider))
this.m_Rigidbody.AddForce(lDirection * this.m_Speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
}```
Thanks for help
Is there a way to tell if a texture in a material has changed from script?
Why do the Unity docs refer to IL2CPP as a virtual machine?
The term seems to be loosely defined but I thought it implied run-time handling of an instruction set like the .NET CIL, if it's done at compile-time then it's just a compiler
Or maybe if there is enough run-time abstraction on top of things like memory, it's still considered a virtual machine?
Which document refers IL2CPP as VM?
Mono and IL2CPPโs scripting virtual machines (VMs)
https://docs.unity3d.com/Manual/performance-memory-overview.html
Unityโs managed memory system is a C# scripting environment based on the Mono or IL2CPP Virtual Machines (VMs).
https://docs.unity3d.com/Manual/performance-managed-memory.html
Yeah seems like it is referring it VM as language runtime that manages memory and resources
Any ideas on why transform.Translate jitters? This is the first time I've had it behave this way.
-The translation is handled in FixedUpdate, everything else is Update.
transform.Translate(Time.deltaTime * player.walkSpeed * movement);
-walkSpeed is consistent and unchanging
-movement is consistent and unchanging (ex. moving left results in Vector2(-1.00, 0.00))
-Time project settings are unchanged from default (0.02 fixed timestep, max timestep 0.333..., timescale 1)
-Based on one forums answer, I've tested with Auto Sync Transforms both enabled and disabled, there's no difference.
Guys, I found out how to properly obfuscate code so nobody will ever be able to read/steal it.
-Don't use obfuscation tools
-Ctrl+A to select your entire script and "Join Lines" to convert your entire 15,000+ lines of code into 1 line.
-That's it, you win.
(satire)
you can write your own language then dont let anyone know how to use except you, you win (satirer)
What can write to the albedo gbuffer? I am displaying just the albedo gbuffer texture
and its not just albedo
its like albedo affected by metallicness
using the gltf importer shader
this is pretty arcane
you have exceeded our knowledge
sorry was being stupid
its combined in the diffuse albedo and specular albedo
got it in my head that diffuse albedo was just albedo, not just diffuse albedo
albedo is albedo. math is math.
lol
Trying to change intensity of hdr color through code. If you do myColor x myColor, is that the same as doubling the intensity?
oh, found this actually
hey everyone,
this might not be the right place to ask, but does anyone know how i can implement steam's microtransaction api into unity? or at least send me a link to documentation? thanks
microtransactions ๐
fr
I remember this
<#๐ปโcode-beginner message>
Seeing a warning about unreachable code here, which doesn't make much sense.
Ahh, the loop always bails.
Never mind that makes perfect sense
Perfect
hello
Is it possible to rotate a mesh in Unity,or must I open Blender? https://old.reddit.com/r/Unity3D/comments/10ppd7l/can_i_rotate_a_mesh_without_a_gameobject_in_unity/
0 votes and 1 comment so far on Reddit
Would be easiest to do in blender
Overly complicated using unity
If you have to do it procedurally it isn't that diffcult actually. Given you have a bit of logic and math knowledge
So I'm looking to pack up an animation state and send it over a network, so that it can be recreated perfectly. Is there generally a good way of doing this efficiently?
So like if multiple animations are being blended together, I need to get that somehow, along with the current animation %
C# question: How do I tell if a Type is a string or an int?
I cant do a typeof on those
in what context
Why
I've got a function, that turns a Type into a string. For most Types it will be just the name, but I have a few special cases for string, float, int, etc
it's for an editor tool
not a plugin. it's, a utility
And why canโt you do myType == typeof(string)
oh. well. i can... do that, yeah. A switch statement was giving me nonsense so I thought i couldnt do it. I may need to go to bed. Thanks
You canโt use typeof for switch case bc typeof does not count as compile time constant. However you can do type pattern matching with actual object
Ha, just tested another case, already ran into an issue ๐ Nvm, I delete that
Indeed, that's not how it works lol
Hi Everyone ๐
I want to create a referral programme in my android app that i'm developing in unity. The android way of referrals uses the Play Install Referrer Library to retrieve the information of the referrer if the app is downloaded using a referral link from playstore. I'm not able to find out how to do this in unity. Found some plugins in asset store but they don't seem to frequently used or maintained. Would highly appreciate some expert advice on how people do this in their Android/iOS apps.
Not a good way. Types in different namespace can have same name.
Typeโs name is not a type
This attitude tho ๐
How are you gonna use nameof for full name? Lol
He will ignore any suggestions against his solution, so, dont keep trying ๐
Oh itโs okay my goal is not convincing him
My goal is to show that it is a dumb idea so no one else do that
when you update a game, does it change the save json that is in place? Or is there something you have to add to your json save that makes it stay even when the game gets updated?
Not sure what you mean? what json, where does it come from?
I have a json save script, It saves on a button, it loads when the app starts, But I was wondering if it will clear the json when i update the app, I save to the path Application.persistentDataPath + "/saveFile.json"
If you do not remove the app, it will keep the json file because its in an extra folder outside of your app source
alright, sounds like a uninstall will clear data then yes, which I would expect it to
yeah the OS will remove all relevant data if you delete the app. onAndroid I think it even asks if it should keep the app specific userdata or not. not sure baout that tho
I will have to test that, thank you for your time twentacle!
No point in joining the conversation if you're just going to throw your opinion around instead of helping.
I already have given a better solution. Either use if instead of switch-case or do type pattern matching.
What is a good way to approach memory-leaks? I pressed one of my buttons, and it just froze Unity, and in task manager it was like inflating with memory.
you have to just think through your code and try to find the infinite loop (which is what I am assuming it is)
'while' loops are the first place to check
then 'for' loops
wait infinite loops can cause memory leaks?
Unity has a profiler
No, it can't
I have 4 toggle options which are part of a group so only 1 can be selected at a time. The behavior works correctly but for some reason the checkmark does not appear when it is clicked even tho it is selected. Anybody have an idea why that might happen?
Well an infinite loop will be the larger concern
I am assuming when you say it "froze unity" that it didn't unfreeze
You should check your code for methods that implement IDisposable, and make sure those are handled.
Unless you wrote unsafe code
Then the problem is bigger
yeah i don't use idisposable
A memory leak usually doesn't freeze Unity immediatley
Just check your button code. If you click the button and it freezes, the problem is there somewhere.
yeah... but an infinite loop would...
can you explain your issue more clearly @brittle sparrow ?
If you are talking to me. I have no code on those buttons just a simple group with with 4 toggles
it used to work before i changed images but I tested the same images on a new one and it worked
No I was talking to compile error
it's nothing much it's just Reset Data breaking
oh sorry haha
yes, but you say Unity freezes and inflates with memory
So show the code of that.
does it ever unfreeze?
actually if it happens with Save/Load data then great i have less code there
yeah posting screenshots
okay cancel! I put a for loop without an i++ jesus
thanks everyone i looked more clearly at my code
sorry for wasting your time
how would that ever unfreeze then?
yeah..
what do you mean "yeah" holy cow I have asked whether or not it unfroze or not like 4 times lol
oh
like did it or did it not unfreeze
your integer never increases...
no it just stayed frozen so I moved down to taskbar
how should it ever reach 2 if you do not set it to i++
yeah the problem is fixed though
okay yes so the whole discussion about memory leaks was pointless, which is why I was asking
sorry
hey
so basically I have a turret, it has an arm and a weapon
when I give it a Vector3 as target I want it to turn at a certain max speed towards the target
how can I get the required angle/rotation in order to face the target?
the direction vector is always (targetPos - currentPos).normalized
and you can just plug that directly into Vector3.RotateTowards
@normal stump Vector.Angle or Vector.SignedAngle is something that I'd normally use too
Regarding the max speed, you could look at using Vector3.Lerp, or Mathf.clamp to set a hard limit on the rot speed
ok
Im currently working on how ram works stack and heap and i wonder something. Value types are allocated in stack and reference types are allocated in heap basicly i know this is not true but let me ask my question. lets say i have a test class which inherits from monobehaviour. I declared a private int x = 5; this "x" is allocated in stack or heap? I mean its value type yes should be stack but its in a class so im kinda struggling here. is it allocated in heap now?
im having hard times with heap and stack
Hello, I'm not really good at english so sorry first,
I'm using Photon and I can't give a nickname to player.
This code gives NullReferenceExpection error. I'm sure the object which has this code has Photon View component. What can be reason?
GetComponent<PhotonView>().Owner.NickName = "player1";
User connects to master, lobby and room before this.
Class C inherits from class B inherits from class A
I have an object of class B.
I want to check whether the object is also class C.
Can I say:
if(B as C) { //stuff } ?
Value types are only allocated on the stack if their lifetime is short. If you're allocating them in a class then that's not the case and they are boxed into the heap
when i declare an private int in a class will it be allocated in heap?
If this is C or typeof C I guess?
I think it will be boxed into object
Sorry I don't quite follow
you can say if(this is YourOtherClass) or if this.GetType() == typeof(YourOtherClass). not tested, but something like that ๐ intellisense will fix my errors ๐
Oh cool that makes sense! Thanks:D
is there a way to move a game object INSIDE a camera's filed of view (orthographic camera), I want to move my Object to the lower right point of the camera Field of view
you can cast from screenpoint to worldpoint to get the extent maybe
This link has your answer:
frontObject.transform.position = Camera.main.transform.position + Camera.main.transform.forward * distance;
in the field of view, not in front...
So I have a towerdefense type game. My issue is that I could place weapons on other weapons cell which should be occupied. Here are my scripts for them.
Mainscript is in Update function.
Main Script: ```cs
if (mapManager.IsWeaponArea(mousePosition) && !mapManager.IsOccupied(mousePosition))
{
//My stuff
}
Second script:
```cs
public bool IsOccupied(Vector2 worldPosition)
{
Vector3Int gridPosition = map.WorldToCell(worldPosition);
//This if statement is broken I think, it blocks the player from placing the weapon everywhere except the cell where mouse was during the click.
//If I remove Input.GetMouseButtonDown(0) I can't place the weapon anywhere.
if (!occupiedTiles[gridPosition.x, gridPosition.y] && Input.GetMouseButtonDown(0))
{
occupiedTiles[gridPosition.x, gridPosition.y] = true; //Mark the tile as occupied
return true;
}
else
{
return false;
}
}```
I did read this a bit ago.. they are placingthe camera to see the object not the other way around
wait that is a different page
The line I send does the opposite though
They are placing the object in front of the camera, thats not what you want
yeah I need to know the point of the lower right point of the camera
i am looking into it
Thats what I said. You should check ScreenToWorldPosition and the camera values like clipplanes and/or screen size
Can't you just get the bounds of the camera, and do what I showed?
Camera.main.transform.position and you move the object to the bottom right depending on camera bounds
oh my god ๐
I am looking into it ... my head hurts a little so I am a little slow
You're programming!!
Part of life
true
Hello, I like using if statements as guard clauses, to stop further code execution inside a method if the if statement is true.
However, when trying to do that with an inherited method, it does not seem to work. Regardless of the StartActivity base, code keeps executing in the child class. Can someone point me towards a solution to this ?
.
I still didnt get an answer to my question (i cant figure it out either). when i declare a value type in a class, will it be allocated in heap or stack
GetComponent<PhotonView>().Owner.NickName
GetComponent<PhotonView>() can be null and then Owner can be null.
Check if your gamobject with this script has a PhotonView, and then check if it has an owner. You can also just add 2 debug.logs in front of that line with these 2 parameters.
I will test this, thanks
Because return only accounts for the base method
Yes, the owner is null. But what is the solve of this?
If you want this, you should throw an exception instead of return
And try-catch it. The if-statement should not happen with normal behaviour anyway
Is it possible owner is null, or should it never be null?
If it's possible to be null, change the line to this:
var photonViewComponentOwner = GetComponent<PhotonView>().Owner;
if (photonViewComponentOwner != null)
{
photonViewComponentOwner.NickName = "player1";
}
If it's not supposed to be null, you should figure out how it can be null
You can also change your code to this for a clearer error.
var photonViewComponentOwner = GetComponent<PhotonView>().Owner;
if (photonViewComponentOwner == null)
{
throw new Exception("owner is null!!");
}
photonViewComponentOwner.NickName = "player1";
Well, it can't be null :(
I don't know photon. I assume you're missing some settings
I'm not sure, I never used Photon, but given the information it would have been either of those 2.
You might want to ask in #archived-networking, some of those people might actually know Photon.
Thank you all ๐
Hey I'm using this currently and it's working great
Everything so far worked except OnTriggerExit (but OnTriggerEnter works)
||I read that it could be a bug or a weird behavior where events are raised for children on enter and for parents on exit..||
Am I missing something?
void _OnTrigger(Collider other, bool entering) {
//Common stuff
if (entering) ...
else ...
}
void OnTriggerEnter(Collider other) {
_OnTrigger(other, true);
}
void OnTriggerExit(Collider other) {
_OnTrigger(other, false);
}
How do you know, it is not working? No Debug Log I see so far
In log it says enter enter enter......
But 0 exit
I didn't include the full code here
Okay, just wanted to be sure bout that. Do you see you exiting the trigger actively, and how are you moving into it? with position or with phsyics movement?
You should log what entering equals to. If it's true or false.
Also, where did you read about there being a bug?
UnityFrustum generates a frustum-shape mesh collider while drag-selecting with mouse
The mesh collider is set to convex trigger on both objects, with a kinematic rigidbody
The frustum mesh is updated in FixedUpdate (according to the readme)
void _OnTrigger(Collider other, bool entering) {
//Common stuff
Debug.Log($"{(entering?"Enter":"Exit")} :: {other.gameObject.name}");
if (entering) ...
else ...
}
void OnTriggerEnter(Collider other) {
_OnTrigger(other, true);
}
void OnTriggerExit(Collider other) {
_OnTrigger(other, false);
}
If you move it with the mouse, it might just miss the moment, where it exits the collider, cause you ignore the collision
oh wait, not mouse but on fixed update?
how do you move it tho, transform.position or physics based?
The movement of the frustum shape is handled by the package
Imagine a 2D rectangle converted to a pyramid
its nice that you explain the setup, but we need to know if its physics based or not ๐ If its just transform.position it, the trigger exit might be missed. Can you , just to test, add a force to the object, so it just flies through the trigger collider?
it's not working for some reason
I'll ask the question again then
I have this turret
I only want the arm to rotate on the up axis to face the weapon towards a target
how can I get the required rotation for just the arm
I have tried moving the entire thing with quaternions
var direction = (target.position - transform.position).normalized;
// 1st attempt (this moved the entire prefab)
var lookRotation = Quaternion.LookRotation(direction);
var s = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * MaxArmAimSpeed);
Oh i went to something different
Yes the object (camera) is placed with position
So I would test with physics movement to see if all collisions get called, because moving a rigidbody with position might just miss your colliders. The enter might just work because on the next frame your collider is inside the other and triggers the enter
The other object is placed with NavMeshAgent (position also I suppose)
True I suppose I need to use enter alone and somehow detect exit when it stops entering
(accuracy is not vital in my case)
How can I invoke a function on the main thread from a background thread and return a value? I'm currently using a concurrent queue to enqueue a command that is dequeued and executed on the main thread, but I'm unable to return a value to the background thread. How can I do this?
thats not gonna work. Entering happens only once. you could check OnTriggerStay
So you want
MainThread
=Call=> BackgroundThreadFunction
=EnqueueToMainThread=> MainThreadFunction
=ReturnToBackgroundThread=> ReceiveFunctionValue ?
This is only possible in Unity2023
in my case every time I move the mouse (collider moves) as long as im selecting (collider is active)* it calls OnTriggerEnter (logs a million times)
Sounds like you want Unity work done on the main thread. You know Unity always works on the main thread by default, right? So unless you explicitly make a new thread, working with an async-await pattern is done on the main thread in unity.
I have a HttpListener working on a background thread listening for commands. These commands need to execute behaviour on the main thread and return a response
The way I have it set up is that it invokes a strategy which returns a type which is then serialised and send as a response
I'm only implementing the strategy behaviour
I would suggest creating a Monobehaviour that you can add Action delegates to in a list, and have this Monobehaviour execute all methods in the list each time Update is called. This is not able to return the value to the thread though.
Maybe show your code if you can. Is it working with Task.Run()?
Also, my solution should use a ConcurrentQueue, not a List.
Giving it back to the calling thread is very complex. Not sure if that's possible. You would need to maintain access to the context, which goes over my head.
Something like
public interface ICommandBehaviour {
public CommandResponse HandleCommand(ICommand command);
}
On the background thread a HttpListener is running and waiting for requests.
In pseudo; Wait for request, parse request, get response from ICommand, serialize it and respond.
Is there a reason that you have to hop on the mainthread?
Even if they have been precollected?
precollected?
Before you run background thread, do oyu have your components ready?
They are referenced if that's what you mean
private async void WaitForData()
{
while (WebRequester.requesting)
await Task.Delay(1000);
await Task.Run(() => {
=> This is in a background thread afaik
Debug.Log(products.Count);
});
}
So the async void is mainthread, the task.run is background
Correct me if I am wrong ๐
Yeah thats what I meant, but even if not, it should work probably
Just to clarify, afaik, you can not call into a thread itself. You can just call a thread and add events to it so it will run them whenever you want them to be called inside that specific thread
It's a server that is running on a background thread, not a client. I've just tried manipulating TextMesh from the background thread and it crashed afaik since no response was received
A server? How do you specify that, are you using netcode or what makes it a server? Just trying to understand your setup
It's just a simple HttpListener
I have a component which starts the listener on a background thread
Okay, then just make your mainthread call your events list and feed it with the background thread?
Don't use async void
Use async Task and handle the process
async void is going to crash your system as soon as anything goes wrong
This was a quick example from my code... the background thread as I mentioned in the code part is only the Task.Run(); ...
I'd have to pass the result back to the background thread which is the issue
Same for the background thread, have a list of events that updates your values maybe?
The problem with this is that you can't go back to the same context. What are you trying to do? Does your listener need something from the main thread that can't be done on the same thread?
you can also have a callback object that just holds a state. This gets send to mainthread, mainthread updates the state and your backgronud could listen for those objects to change. Thats just theory, might work
I currently have
// Background thread
public CommandResponse HandleCommand(ICommand command)
{
commands.Enqueue(command);
// Somehow return the result
}
// Main thread
void Update()
{
if(commands.TryDequeue(out ICommand command))
{
switch(command)
{
...
}
}
}
I guess you gotta go with some object based approach
In WPF you can get the dispatcher for the main thread to invoke on there. Is there no such way to do it in Unity?
What is it actually doing for the background threads in your wpf example?
I already told you that there is a way as of Unity 2023
Doing this manually is not possible as far as I know
โ๏ธ
Perhaps you can use TaskScheduler.FromCurrentSynchronizationContext() to get the current context, which I have been hinting about for a while now. Since this goes way over my head I can't give you a solution that uses this, but this seems like a start when it comes to switching threads, since it depends on the thread context.
Perhaps you can use my previous solution of creating a monobehaviour to store a ConcurrentQueue of Action types, and have them accept a context from this method. Maybe the main thread can then send the response back as an object, after a main thread handles this queue.
@plucky inlet I ended up using OnTriggerEnter + short timeout delay
Works great for my usecase (accuracy doesn't matter)
So it keeps updating the time while still colliding
And it skips selection if it hasn't collided for x time delay
After a small test, looks great even tho it's not accurate
I had a dispatcher somewhere, ill check later on my scripts ๐
Here is something I made 3 years ago that acts like that dispatcher @wispy fable : https://hatebin.com/tlkbntuldf
Background to Main and back threading
i need help figuring out if a eulerangles.y angle is between two other angles
for example:
the players eulerangles.y angle is 349
and i need to find out if its between 281 - 101 (which it is) but idk what to write to check this the way i want to
var from = SplineRotationY - 90;
var to = SplineRotationY + 90;
if (from < 0) fromFixed = from + 360;
else fromFixed = from;
if (to > 360) toFixed = to - 360;
else toFixed = to;
if (player.transform.rotation.eulerAngles.y >= fromFixed && player.transform.rotation.eulerAngles.y <= toFixed)
{
player.splineDirection = true;
Debug.Log("forward");
}
else
{
Debug.Log("backwards");
player.splineDirection = false;
}```
this is what ive wrote but im not a programmer so im pretty sure this is wrong
Quaternion.AngleAxis + Quaternion.Angle also works
ill try that, i cant get the railSpline.transfrom.forward i can only get its position and rotation
Quaternion.Angle(Quaternion.AngleAxis(AngleA, Vector3.up), Quaternion.AngleAxis(AngleB, Vector3.up));
Also, eulerangle is between -180 and 180 if I remember correctly.
im a little confused on how to use this to find out if the players angle is between the 2 angles like i described
angleDiff = (player.transform.rotation.eulerAngles.y - SplineRotationY + 180 + 360) % 360 - 180;
if (angleDiff <= 90 && angleDiff >= -90)
{
player.splineDirection = true;
Debug.Log("forward");
}
else
{
Debug.Log("backwards");
player.splineDirection = false;
}```
figured it out
the formula is angleDiff = Quaternion.Angle(Quaternion.AngleAxis(player.transform.rotation.eulerAngles.y, Vector3.up), Quaternion.AngleAxis(SplineRotationY, Vector3.up));
The number will be between 0 and 180
Is it possible to loop through each SerializeFields in a Header?
Or rather loop through the Header looking for each SerializeFields
You mean the header attribute?
typeof(myType).GetProperties(accessorFlags) gives you PropertyInfo[]. Each PropertyInfo has a getCustomAttribute<TAttribute>() method to get the HeaderAttribute. If it's not null, you reached a header. If you want a specific header, you should check the attribute that way.
accessorFlags in this case is the flags to search on. I forgot what they are called. But you should check for instance, and private/public depending on what your properties are
If your serializefields are actually on fields, you should do typeof(myType).GetFields(accessorFlags) instead
Guys i need help with code, someone help?
@swift falcon what is the exact thing you want from this? I can try and create something
Since it's probably confusing
?
Click the link
I was trying to play around with your response but you right. It is confusing haha.
I have a Header with SerialeFields like such
[SerializeField] private Button levelOneButton;
[SerializeField] private Button levelTwoButton;```
etc...
I want to loop through the Header to disable/enable each button
there was nothing special?
Point is, don't ask to ask
Well reflection can do that, but it's very complex as you can see
You should probably create a script that disables them all manually...
But, since I'm bored, I can make an enumerator for you.
I'm just unsure what myType and accessorFlags are
Or are you just trying to postpone work :3
I'm trying to have a component be able to save while in play mode
Define save
Well, I'm stuck
And ChatGPT aint helping
Ah, same
F
what i mean is to save the values changed on a component while in play mode
cinemachine has an implementation for it
that it says can be used for other components
Use Scriptable Objects
If you change a value of a Scriptable Object, it'll be saved after you close the scene
Though this is only in editor mode
Don't try to use it as a save system
mostly i want to get this to work, but it doesnt work as it claims to
so i want to know if im missing any intermediary steps
I mean it's only for tweaking and later it won't be used anymore right?
Also show the code to see if you applied it properly
And #๐ฅโcinemachine might know more
it might be used as an internal tool
SO can also be used as an internal tool
But I'd check out #๐ฅโcinemachine and share your code as well so people can see if you applied it properly
And always 

,maybe there are some solutions online
i tried
there are other solutions for which i might have to adapt their code (which is fine ig, but this will save me a ton of time)
I don't know if this is a "Cinemachine Component" since it just derives from MonoBehaviour, but I don't know much about Cinemachine
i checked out cinemachine's own base classes
I'd recommend moving to #๐ฅโcinemachine
myType is the class your fields are in. accessorFlags are these: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=net-7.0
Apparently they're bindingflags
But I would strongly recommend just doing it manually
Reflection for this is unecessary
The way I thought of it is whenever my character reaches the goal I store the index in an int completedLevel. Using that int I enable all buttons up to in completedLevel + 1
Is there another way to do this?
I was writing code for this but it's just a lot to account for every problem that could happen with reflection
Idk what the buttons are, but that's fine I guess
Just use a list to store it
But you should do it manually, and not reflection
What do the buttons represent?
Just the completed level?
But they're only a button that turns on or off?
What happends if they're on?
If you click on it it calls my LoadLevel function
Right and it's disabled if you haven't reached it yet?
Codewise, they are not levels, they are UI elements that load a level, right? So you can just store them in a list or create buttons depending on the last levels you played. all up to you
Right
What about having a List<Button> in your class, and store a reference there?
Then you can iterate until the button that should be on
And you can check that by just comparing current index +1 against the level
[SerializeField] private List<Button> _levelButtons;
private void setLevelButtons(int level)
{
// Disable all
foreach(var levelButton in this._levelButtons)
{
levelButton.enabled = false; // Or whatever the way to disable it is.
}
// Enable
foreach(var levelButton in this._levelButtons.Take(level))
{
levelButton.enabled= true; // Or whatever the way to disable it is.
}
}
Something like this
Then you can also skip levels, and go back
You can't skip levels and keep them disabled, though. That's more work.
It's a linear game so it's fine
Take in this case only returns up until that level, basically
That's why the loops are basically identical
I didn't know SerializeField could make a list, thanks
I believe List works. Otherwise it needs to be an array
Arrays works too with this code
๐ฏ
Lists do work on it afaik
Happy days
Hey guys, I want to be able to construct my damage class via ScriptableObject OR by giving it the specific parameters. Is there a better way to do this or is my approach the best I'm gonna get?
public class Damage : MonoBehaviour
{
float _amount;
float _addForce;
int _tickAmount;
float _damageOverTimeDuration;
DamageElement _element;
public Damage(DamageInfo damageInfo = null, float amount = 0, float addForce = 0, float tickNum = 1 /*...*/)
{
// if damageInfo is null Construct with Parameter values ... else :
_amount = damageInfo.amount;
_addForce = damageInfo.addForce;
_tickAmount = damageInfo.tickAmount;
_damageOverTimeDuration = damageInfo.damageOTDuration;
_element = damageInfo.element;
}
!cs
really depends on your situation. If the values do not change and you want to reuse that a lot, use scriptable objects
thx xD
Is there actually such a function? Or should I just use an if statement on each element to check if the level is before my completedLevel variable?
This is a Linq method
!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.
Pastebin
@swift falcon
๐
Since an array and a List both implement IEnumerable, this method is valid on them
It's not okay to fill a 27 inch monitor lmfao
Linq is the greatest shit you will ever learn about
Well maybe not
But it will help
A lot
I want to be able to choose that in a case by case scenario, Im just wondering if this is the best way to make this "Constructor 2 ways" or if there's a "better"/conventional way to do it
Well you can overload constructors
If thats like a library you want to be able to built from SOs, thats totally fine. But again, if you have like a database, cause your game will be based values from that, its better to use a class that just gets fed. But if its like an item you assign but in your case a damage you assign to something, sure, why not
New start, sry for the codeblock. Has anyone an idea how to make this shorter or "better"?
Link: https://gdl.space/yosesixeji.bash ๐
Anybody?
Gonna look into this
Thanks for the help!
if(!vInput)
{
_animator.SetFloat(_animIDvInput, 0, 0.1f, Time.deltaTime);
}
What is vInput and what is _animIDvInput? is it the same value?
Picks the one based on parameters @floral needle
It's the same as method overloading but then for constructors
vInput is a bool varaible if "w" or "s" is pressed. So if there is an input on this axis. animIDvInput is the float value in the animator which changes the animation. I think 1 is walking forward, -1 is walking backwards
cant you just get the float of the axis? as it will always return something, either 0 or whatever value you throw in as input?
so setfloat on the animator all the time, without if statements
Also I forgot to give the variable a name but shhh
You're not supposed to use the constructor in a Monobehaviour. Instantiate the Monobehaviour like you're supposed to in Unity, and create an Initialize method. You can also make overloads with this like @woeful leaf mentioned.
Also that
i.e.
public class Damage : Monobehaviour
{
public void Initialize()
{
}
public void Initialize(int val)
{
}
public void Initialize(int val, string val)
{
}
}
what is Initialize method? Did I skip a part in unity beginner?
No it's just a method he made lol
It's a method you make yourself.
i could try that. But my questions was more is there a better way to get the inputs of the single keys or do i have to check for every single key with a new if statement?
Not going to lie, this was my first thought, but I (dreamnt) remembered reading somewhere that you couldn0t do this. In retrospect, that's literally what I see when I ctrl + click on a Method to see the overloads xD
Derp moment
just something you Initialize() in awake?
It's also used a lot by just the functions given of C# and Unity
oki oki
You can bind keys to your value, so they create an axis which makes you return 1 on W and -1 on S. And than you just ReadValue from the input and get the vector or float for your animator
But this will bind you to a gameobject you put your monobehaviour on to have different dmg components, just keep that in mind
will try that, ty
I dont get it 
If you use monobehaviour, you have to use it as a component. If you just use it as a class, you can create it just for data source that then can be used in your components on the gameobjects.
The more I dont get it ๐ฅน
You probably want to look into Scriptable Objects
This is a good way to set data. But this is more for oak.
Just think about how you gonna set up your damage on your items. can you explain that? Do you have like a gameobject of a weapon and than add damage component to it, which is what you get with your monobehaviour?
But if you have like a scriptable object item, you could reference a field to the scriptable object damage for example, and from there you just drag drop and create your stuff simpler. But you gotta explain a bit what you want to do with damage
I don't understand the behaviour my code is giving, why would it snap onto it if the pointer is not anywhere near the actual item? Am I just doing something funky with the booleans that I'm not seeing? Here's the code: https://gdl.space/yuhatenaqa.cpp
(Each of those items that you can grab has that script)
Is that UI canvas?
Yes
is the canvas overlay or camera screenspace?
Okay, the problem is, the position of your mouse might not be exactly as where your UI is. Did you try to use WorldToScreen with your mouseposition?
Nope
but transform.position is not what you do on UI
you position it with rectTranform.anchoredPosition
Oh
Lemme see
What's so bad about transform.position then for UI elements
Also I suppose I've to do a GetComponent for it then since I don't inheritely have it
transform.position is usually in 3D space, 1 unit = 1 meter. UI is in pixel based grid, so 1 unit = 1 pixel
hmmm
That is why there are WorldToScreen calculations or ScreenpointToWorld and what not
Righty
And why anchoredPosition over position
Now the position doesn't match the cursor with rect.anchoredPosition = Input.mousePosition;
can you debug log both values?
Cause I guess you gotta set the z value to something to fit it
You can just cast, as you already have the transform
What cast would I use?
to cast your transform to RectTransform
Are Get Set methods common practice in game dev/C#? I haven't seen them often in tutorials
That wasn't what I asked, like what is the syntax for it
I'd think just (RectTransform) in front of it but that doesn't really work
Properties are extremely common outside of gamedev, and still common in it. Proper practice is often overlooked for the minor speed benefit of avoiding the methods
Why not?
I often get a Missing Reference error when I try accessing a variable from another script. The error goes away when I declare it static, would a Get method fix it too?
((RectTransform)transform).position
You need more brackets.
Or you just make a variable on another line
otherwise you would try to cast the position as recttransform
Ah right
No. You probably have not set the variable to anything
you need to get a reference when accessing a public member from another object.
how to get a reference: https://www.youtube.com/watch?v=Ba7ybBDhrY4
Ah could very well be why thanks
That fixes this issue
((RectTransform)transform).position = Input.mousePosition;
I'll watch this thanks! NRE has been the death of me. Sometimes it pops up sometimes it don't lmao
The other thing still isn't fixed though ๐ค
(This part)
https://gdl.space/dikisemuje.cs, can someone tell me how to fix error: NullReferenceException: Object reference not set to an instance of an object
CraftingSystem.RefreshNeededItems () (at Assets/Scripts/CraftingSystem.cs:186)
CraftingSystem.Update () (at Assets/Scripts/CraftingSystem.cs:116)
So did you debug log your rect position and your input. mouse position?
Just realised it should probably be this instead ((RectTransform)transform).anchoredPosition = Input.mousePosition;
craftAxeBTN is null, or gameobject is null
Which does break the position again
So what i need to do?
With that the cursor and the object aren't aligned anymore
Im beginner so idk
I'll go do that now
What line is 186?
and 116
This line is not guaranteed to be called before update I believe
#๐ปโcode-beginner next time.
but you are using toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>(); to get the reference, it seems like that is probably not returning what you expect. make sure you also scroll to the first error in your console because this line is likely throwing an error
But the code is full of these find methods so who knows what it gets
You should get craftAxeBTN in another way
But if it wasn't found:
craftAxeBTN = toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>();
craftAxeBTN.onClick.AddListener(delegate {CraftAnyItem(AxeBLP); });
I would expect the next line to give an error.
So what i need to do?
right but if they are just looking at the last error in the console rather than the first we don't know if that is erroring or not
Debug.Log($"The position of the object is: {((RectTransform)transform).anchoredPosition}, and the position of the cursor is: {Input.mousePosition}");
Oh fair, he could have way more errors then this.
screenshot your console while scrolled all the way to the top. i'd bet you'll find errors on different lines there ๐
That looks good to me tho. Can you show your screen on how it looks?
have a function you call at the end of it. there is no like default callback
or use async Task that returns a completed event.
I get three errors:
It doesn't capture the cursor so to illustrate it, it's the red dot
When you hold the object it yeets it way off to the right and top
- NullReferenceException: Object reference not set to an instance of an object
CraftingSystem.Start () (at Assets/Scripts/CraftingSystem.cs:58) - You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor ()
Blueprint:.ctor (string,int,string,int,string,int) (at Assets/Scripts/Blueprint.cs:18)
CraftingSystem:.ctor () (at Assets/Scripts/CraftingSystem.cs:26) and 3. NullReferenceException: Object reference not set to an instance of an object
CraftingSystem.RefreshNeededItems () (at Assets/Scripts/CraftingSystem.cs:186)
CraftingSystem.Update () (at Assets/Scripts/CraftingSystem.cs:116)
Yeah, so that's what I expected ๐
So can u help me out?
look at that, the line i pointed out that is likely throwing an error is throwing an error
you need to get a reference in a better way than chaining all of these Find calls
how to reference: https://www.youtube.com/watch?v=Ba7ybBDhrY4
Can you show a screencapture of it? Like how it behaves going around the center?
A coroutine has no build in way for this. Coroutines are of type IEnumerator, and these only have behaviour on how to keep going. It has a MoveNext method but this is not for checking if it's finished. You should create a seperate boolean outside the code that turns true once the coroutine is finished.
You mean a recording?
I have about six different managers in my game.
Only two of these are singletons. This is because my learning resources have led me to the conclusion that the singleton pattern should be used sparesly.
The two classes in my project that implement the singleton pattern are the GameManager and the AudioManager.
The other managers in my game, such as the UIManager, InputManager, and CameraManager, are all passed into my GameManager.
If a piece of code wants to reference certain functions of the UIManager or InputManager, for example, it will do so through certain functions I have in my GameManager, which then references the other managers.
Is this bad design? Should I refactor this, or can I keep using it in this way?
I would keep the main managers all singeltons if possible. So you have full control if you need, but you can still have your gamemanager control states that call the UI
that sounds like a kind of bastardized mediator pattern. you could look into how that design pattern works to clean up your current implementation
Ahhhh, I know the issue, i guess at least. ๐ can you show your prefabs inspector of the recttransform component?
Like the inspector of the object I pick up?
can i have the docs link for it thank u ๐
Because this is what a Coroutine is basically
Just for testing. can you take the prefab you instantiate as text, pick that one and set the anchor to this:
Okay, whereever its coming from ๐ Just set the anchors ๐
This should be fine right
Or wait I still need pivot to be 0 as well
That did change the position of it
But it's not in the center
Like it used to be with the old way
You mean in the center of the screen? or what center?
Oh the hitboxes are whack now
Oh you mean the center of the UI object?
the cursor holds it to the left corner of the object
Instead of the center of the object
can you try all anchors and pivot to 0.5?
Ah wait, anchors to 0 and pivot to 0.5
that should be correct
^
Hitbox illustrates it better that it does it properly heh
Indeed it is
Indeed it isnt
No that was an issue of using the Rectransform.anchoredPosition instead of the transform.position I used to use
?
It's not ;)))))
That the it still can get regrabbed for some time even though the cursor isn't over the object
That's what the video shows
how do you grab your object?
too many topics going on ๐
Found the link ๐
:D
are you sure you reset your onMouseOver correctly? Did you check those values?
It's kinda hard to check in that case
Because it's not like consistent
I might have to do with this part
public void OnPointerExit(PointerEventData eventData)
{
if (Input.GetMouseButton(0)) return;
onMouseOver = false;
oneIsHeld = false;
}
Just disable all but one and debug log your values of this one
Maybe it somehow exited it without getting the input or smth
Or some kind of mismatch
UI is behind sometimes, so your code might execute again before the UI position is updated
hence the execution order of Update, OnEnable and UI update
Is it intended they flip to your position on pointer enter, not mouse down?
flip => move ๐
There's no Update "type" for OnPointerEnter, so I've to combine Update and OnPointerEnter to achieve what OnMouseOver would achieve
The latter refers to this function, not the boolean
That function doesn't work for my use case though
@woeful leaf what is the behavior you are trying to achieve?
do you want to be able to drag-to-move UGUI elements?
Yeah
okay
If you click and hold on it it'll follow your mouse position
you could use ```cs
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Its over UI elements");
}
else
{
Debug.Log("Its NOT over UI elements");
}
To check for being over UI
class DragToMove : MonoBehaviour, IBeginDragHandler, IDragHandler {
public override void OnBeginDrag(PointerEventData _) {}
public override void OnDrag(PointerEventData pointerEventData) {
// does not account for canvas scaling. you will have to deal with that
transform.position += pointerEventData.delta;
}
}
I was not aware that that existed
@woeful leaf that's it.
OnDrag, is that working for UI objects?
I thought Drag was for like mobile
you don't need a collider
I have one
I am though
what does @woeful leaf mean by physics?
it isn't going to change the correctness of this script
It has a rigidbody
Yeah it uses the velocity of the rigidbody
And the collision to collide with other objects
i think you are at the start of a very long journey
;-;
what is the game?
Oh did not know you can use OnDrag on UI, because it acts like a "collider" already, thanks ๐
yes, EventSystem requires raycasts, not colliders nor physics, and GraphicRaycaster supplies eventsystem with raycast information for UGUI
in order for an object to receive OnDrag calls it must also have OnBeginDrag, which is a code smell of this api
just read the docs about UI OnDrag. Good to know for next time!
But well, here you have your solution @woeful leaf just use doctorpangloss code with your positioning of recttransform ๐
it really depends what the game is
Let implement it and see what it does
@woeful leaf
there are three ways to move objects:
1 by changing their transform's position
2 when an object has a rigidbody, moving it kinematically (its velocity is derived at the end of the frame)
3 when an object has a rigidbody, moving it with forces (its velocity is natural)
when you want to move an object naturalistically using the pointer, and the object has a rigidbody, and you want the rigidbody to behave physically and naturalistically (#3), you can use joint drives between the rigidbody and an object whose position is being changed by the pointer's delta
#3 is really complex but you can find a lot of examples online
Although 3 would be cool to implement, it is not needed, nor do I have the time to implement it. And I don't even know if it'd fit the game heh
Currently it's just 1.
I know but I don't have like very "real" physics
The only thing that it has is a collider and a set velocity on the rb
you are doing #2 then
And also 1.
You can still use the transform.position, if you want to ignore phsyics while dragging. So, I do not think its for us to determine your game here ๐
okay
dragging objects around with a pointer in a general sense is hard
this is the script i provide to folks who use my technology, because it is such a common ask and it is so hard: https://github.com/AppMana/appmana-unity-plugin/blob/master/AppManaPublic/InteractionToolkit/ThisDraggable3D.cs
since you don't need a general solution, if you can tell me what the game is, i can make a specific suggestion
just eyeballing it, there's a lot that's sort of flawed about how you architected your game
:(
@woeful leaf here's an example of this dragging script in action
https://appmana.com/watch/theheretic
you can try moving around the lights, flicking them, rotating the camera, and if you visit on mobile, you can use multi touch
An AppMana Streaming Experience
public override void OnDrag(PointerEventData pointerEventData) {
// does not account for canvas scaling. you will have to deal with that
transform.position += pointerEventData.delta;
This appears to banish the objects to the shadow realm
in order to give you a script that works in your specific case, you have to answer my question what the game is
It's quite a simple game really. You've these passwords that fall down, the passwords that are bad you put in the red box, the ones that are good you put in the green box
okay
attaching rigidbodies to ugui elements typically does not work very well. it requires understanding way more nuances than you will comprehend. let's pretend the rigidbodies don't exist, since for now, other than for the dropping physical effect which is easy to do in code, you don't need them.
1 set your canvas to screen space overlay
2 then use the script i provide
if you want to use screen space - camera, you can try transform.localPosition += pointerEventData.delta, but i feel like i am just programming this for you and you don't really comprehend yet a lot of stuff
so it really depends what your goals are
both are
both
?
I've two canvases
okay well
One is for the passwords
i think you'll figure this all out
The other is for the rest
i think you can google "dragging sprites unity physics" and you should probably not use canvases at all. you can use TextMeshPro Text (not the UGUI version) to make the text labels
then it will be more intuitive for you
transform.localPosition will resolve your issues with pointerEventData.delta in this case
I made like everything without googling except the IPointer events cuz OnMouseOver didn't work
This does work now actually
OnMouseOver is deprecated
is it possible to make y = 0 while keeping the same rotational axis? on a quarternion
It matches the position instead of yeeting it somewhere3 else
for that matter so is Input.GetMouseDown
It's older yea
Yeah there's a new Input system I know
the pointerEventData is giving you all the information you need about the pointer
Anyway thanks for all the help, I'll go expirement a bit with the OnDrag and see what that does for me
Does anyone know if it is possible to convert a .texture2d file to an exr file? Thanks
Googling gives me this: https://docs.unity3d.com/ScriptReference/ImageConversion.EncodeToEXR.html
Can someone give me a quickie? If I have a worldSpaceMatrix and an offsetMatrix, and I want to subtract the offset, is it as simple as worldMatrix * inverse(offsetMatrix)?
Do you know how I can use this script to convert it?
Doesn't the example do exactly what you want? Or am I misunderstanding the question?
yes, it does what I need but I don't know how to apply it to my .texture2D file
Oh, I thought you had a texture2D in your code and wanted to convert that.
You have a texture2D file, make a texture2D in code, and feed it into that method.
I present you the most inefficient (I think) isometric wall fading. https://streamable.com/thd64x
https://codeshare.io/eVb96b
I have this script attached to every wall. When the scene becomes bigger more walls I will have. What can I do to make it better?
Hi, does OnEnable gets called every time the object is set active?
Yup
guys I have a question,
button.onClick.AddListener(() => DoSomething(CalculateSomething()));
If add a listener to a button like this, which calls a function, and "CaluclateSomething" will return some sort of value. Will the value that is return from CalculateSomething be called when the button is clicked or when the listener is assigned?