#archived-code-general
1 messages Β· Page 132 of 1
And people wonder why I have started separating my code from editor scripts...
[ShowIf(nameof(loadSettings) + "." + nameof(LoadSettings.IDType), SceneIDType.byName)]
public string sceneName;
[ShowIf(nameof(loadSettings) + "." + nameof(LoadSettings.IDType), SceneIDType.byID)]
public int sceneID;
public LoadSettings loadSettings;
[Serializable]
public struct LoadSettings {
[ShowInInspector]
public LoadSceneMode LoadMethod { get; set; }
[ShowInInspector]
public SceneIDType IDType { get; set; }
[ShowInInspector]
public SceneLoadType LoadType { get; set; }
}```
Working on a code generator that creates wrapers from interfaces, will also be able to put default attributes where I set them to show up.
why is there an error
You need to configure your !ide so you get proper error highlighting and autocomplete
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
but I already installed via unity hub
nvm
i have to configure
@quartz folio i dont get it, everything is alrd set
fixed
Is it possible to do web gl unity with 3d/2d avatars, text to speeh + animations? I see some mixed bags of features but nothing that's quite there yet
Sorry w/AI
i had to regenerate files
- Can i precalculate width of a configured tmp text based on a string on condition, that the string fits the resulting width? I.e. know how wide the text should be to fit the string inside
yes public Vector2 GetPreferredValues(string text)
this is under tmp text
hi guys idk if you guys know how to fix this but my VS is rlly weird
like there arent any red squiggly lines under anything ever and some things arent coloured, or arent autofilled if i press tab or enter or something
also ik this isnt rlly a unity issue but still
is your !ide configured
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
what does that mean
Ide the code editor
your visual studio (its your IDE) needs to be configured to work with unity stuff
VS doesnt come with unity stuff right when u download it
how
theres a big command right under my message
ok
did anyone try to use com.unity.runtime-scene-serialization?
it looks really convenient for asset importers to create prefabs so I can create them in 3rd party dccs
the only thing I'm struggling is AssetPack in serialization metadata. it supposed to be lookup table for assets so it can stores ids which makes sense, but I have no idea how to actually create this table by myself.
seems simple but api is so cryptic
god we need proper usd support
all this NIH features are spreading like cancer
do you guys have any good resources on a state machine?
You can read any articles online, not only for Unity/c# specifically and they all will still be applicable in your game
Nothing fancy regarding state machines, it's just the name/terms that made it look like one
it's not very complicated, you can handle that by using articles online as slimstv said
Hi , I have callbacks that come from an external source, and as I have read multiple times that unity is not thread safe, I use the "unitythread" class explained here: https://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread My question is if this is a correct solution for handling with this type of callbacks or there is a better solution (as the answer is from 2018)
you'd need to do your own dispatching
or just the simplest way by queueing your thread into monoBehavior
wrap it in a delegate and you can use ConcurrentQueue to queue all those calls and have it run on Update
void Update()
{
while(myConCurrentCue.Count > 0)
{
//dequeue and invoke from MonoB
}
}
just a simple and ugly example, but you shoould get the idea
so the "UnityThread" script from the stackoverflow answer is too complicated for the thing I do? Because it works, its just that I dont know if its the best solution for this.
if it works, then it works π
Does the callback come from an async method? Why don't you just use events?
Unity is thread safe when you stick to Tasks, because the synchronizationContext in Unity is redefined to run everything in a safe thread that won't throw exceptions because Unity methods can't run on seperate threads.
The only reason to dispatch it back to the real main thread is to avoid race conditions, but you also have concurrency tools for this
this is not true...Task.Run BOOOOM yoou dead
Yes, that's why you don't use this and invoke an actual Tasked method
There's no need to manually invoke something from the Task factory
Unity works fine when you declare an async-Task method, so you don't need to create a whole invokation machine to fix something that isn't broken, unless you manually create threads or use the Task factory
Honestly I'm surprised Task.Run doesn't run either
Its a callback that returns some coordenates from an eye tracker, like 30 times per second. I tried using events but I dont know why after some seconds sometimes it just stops working. Then I thought it may have something to do with threads, and I tried this "unityhread" thing from stack overflow and it works. Maybe the error comes from another source I dont konw hahaha I just wanted to know if there is a better method at handling different threads. Im just learning so there are a lot of things I dont understand π I dont event know if that is an async method or not
Events don't just stop working, so it must be something else
So that's weird
Anyway, that unityThread is also nice. It basically saves delegates (so anonymous "methods"), and invokes them in an Update method, which guarantees to run on a supported thread. I see it also supports Coroutines. You can totally use it
I don't know how threaded that eye tracker is, but I would assume they atleast account for proper threading.
ok, thanks, I will just stick to that then π
Hey, I'm trying to crop a sprite at runtime through a script. I've figured out that I can do it using Sprite.Create() but it's a bit awkward. Is there any other way to do this? Also, I want the sprite to animate but when I do this it stops animating, so is there anyway I can crop every frame of an animation?
I do not know how, however I can say to you that you need to ask yourself if it is truly necessary.
Hey, I'm trying to understand (using the old unity input system) if the player is using (or has used) the keyboard or the gamepad. any suggestions please?
Input.GetKeyDown(); ?
no like i want to detect if the last button pressed was on keyboard/mouse or on a controller, so that i can know wether the player is using a gamepad or a pc
Oh, the old input system is not good at that. I would suggest you upgrade to the new input system or rewired.
Using the old system? Good fuckin luck
ik, thanks, but it's much better for custom keybinds
It is not.
idk what old input system you are talking about
The Input class
i mean the one that uses Input.GetKeyDown for example
using the old unity input system
exactly
Yes that's the old system
this one
This cannot easily indentify controller.
And it will be very hard to do what you want with it
Recommendation is to switch to the new system
You could, make 2 key bind for each binding.
Which can do this pretty easily
One without the gamepad and one with only the gamepad.
https://forum.unity.com/threads/check-whether-controller-or-keyboard-is-being-used-via-script.359608/ i found this but i'm too dumb to know how to use it myself
However, that would be kinda stupid.
elaborate please
but this is working super fine for what i need
You have an Action (Jump)
Bind the Jump on Space Bar
Create an other action Jump Gamepad and only bind the gamepad.
However, the real solution is to upgrade to the new input system.
i have tens of actions
i haven't found a single forum or tutorial on how to use custom keybinds ingame with that
Yeah, exactly. I'm not saying it is a good solution.
Look again.
I use Rewired, so I cannot help you.
hi guys, any know what i need to use a websocket client in unity to connect to our server, what is the best option for work in pc, consoles and mobile?=
It's called interactive rebinding and it's fully supported
is that in the Input System docs? I'm interested in adding that to my game, but I haven't looked into it yet.
I know there's some code floating around in the package
Yes it's in the docs
Hi, I've been trying to build a project which has nothing really special, but for some reason launching the build (no error), starts the process but doesn't open any window (the process also never closes so I have to close it through the Task Manager).
It happens on multiple machines, works if I do the same with a fully empty project.
The log output is basically empty. Using Unity 2022.3.2. Any idea please ? : D
Hello everyone, I'm running into an issue where the mouse sensitivity is different in the editor from the build. Increasing the sensitivity does not fix the issue (build-side) and I doubt it has anything to do with my code. Any input on this? Would really appreciate the feedback.
I bet you are multiplying Time.deltaTime into your mouse input.
(i.e. it's your code)
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
Okay, giving it a go
Hmm, now it's super choppy, full code for reference:
void Update()
{
//if (!IsOwner) return;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
xRotation -= mouseY;
yRotation += mouseX;
//Debug.Log(1/Time.deltaTime);
Debug.LogFormat($"<color=green>MouseY: {mouseY} - MouseX: {mouseX} - xRotation: {xRotation} - yRotation: {yRotation}</color>");
xRotation = Mathf.Clamp(xRotation, -90f, 25f);
//This works properly now:
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
if (player != null)
{
player.Rotate(Vector3.up * mouseX);
//transform.position = player.position + offset; // Set the camera's position to match the target's position plus the offset
}
} ```
shouldn't be choppy - did you reduce sensitivity?
yes
what is it set to
0.0001f
should be around 1ish
that's tiny O.o
too fast
Are you sure you saved?
this does nothing
change in the inspector
I can't. The issue is in the build not the editor
change it in the inspector in the editor
'Build and Run'
no
go to the inspector for your player object
change the sensitivity value there
that value goes into the build as well
Ohh, yea that, the player look is a singleton o.O
irrelevant?
okay
The value of serialised variables is set via the inspector, the value set in code is only the initial default and changing it once set does nothing
@leaden ice @quartz folio It baffles me as to how you guys knew that I had the sensitivity variable as public/ serialized
Making it private fixed the issue
I'm very grateful for you guys. Really appreciate the help
FYI, you can't change variable values of singletons in the editor.
we have seen your issue and similar issues to it thousands of times π
or at least I can't
yes, you can
Aaah, haha, thanks
how does that go?
you find the object with the script on it
and you change the value in its inspector
it exists somewhere in your project
either in a scene or as a prefab
Yes, but the singleton isn't attached to the object, the parent script just references it
MonoBehaviour scripts are ALWAYS attached to a GameObject
they cannot exist without being attached to a GameObject
not relevant
this script is attached to a GameObject in your scene somewhere
But it doesn't inherit from Monobehavior
yes it does
Let me check
because Singleton does
Oh
we also knew it was public because you wrote it here
Oh right π
Ah, you got it, I have the script on the camera
Thanks again!
So an empty project does work, correct?
Yes
Though there is no compilation or launch error, nor warning, just nothing
in your project?
"though" made it sound like you were talking about the empty project
Sorry, yes, I mean no error in our project
so, I'm getting some issues with ViewportToWorldPoint.. Magenta lines are what it detects in code (moves and scales relatively with the camera position)
private Rect GetScreenWorldRect(Camera value)
{
Vector3 bottomLeft = value.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
Vector3 topRight = value.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
return (new Rect(bottomLeft.x, bottomLeft.y, topRight.x * 2f, topRight.y * 2f));
}
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMin, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMax, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMin, sqr.yMax, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMax, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
any ideas?
i don't understand the problem
What are your expectations and what are you seeing that differs from those expectations?
I am trying to get the magenta lines (the rect) to align with the camera edges.
magenta lines are the exact thing code outputs
and the white lines are the camera itself
It's not really clear to me that they are not aligned, as the screenshot is a little unclear
Are you sure you're passing the correct camera in?
on the top right of the magenta lines you can see that the entire white edge is detached
yea
how are you doing it? Can you show the code?
public class windVFX : MonoBehaviour
{
private Rect sqr;
[SerializeField]
private GameObject particles;
[SerializeField]
private GameObject player;
[SerializeField]
private Camera cam;
private PlayerController controller;
[SerializeField]
private float timerMax = 0.4f;
private float timer;
void Awake()
{
controller = player.GetComponent<PlayerController>();
sqr = GetScreenWorldRect(cam);
}
private Rect GetScreenWorldRect(Camera value)
{
float height = value.orthographicSize * 2;
float width = height * value.GetComponent<CameraScale>()._targetAspectRatio;
Vector3 bottomLeft = value.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
Vector3 topRight = value.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
Debug.Log($"Position : {transform.position} Local : {transform.localPosition} Camera Pos : {cam.transform.position} Camera LocalPos : {cam.transform.localPosition} Width : {width} Height : {height}");
return (new Rect(bottomLeft.x, bottomLeft.y, topRight.x, topRight.y));
}
void Update()
{
//Debug.Log("Rect xmin: " + sqr.xMin + " xmax: " + sqr.xMax + " ymin: " + sqr.yMin + " ymax: " + sqr.yMax);
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMin, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMax, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMin, sqr.yMax, 0f), Color.magenta);
Debug.DrawLine(new Vector3(sqr.xMax, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
}
nvm, got it now
Is there a way to get interface variables to show up in the inspector for ScriptableObjects?
how do i make my rigid body walk on a sphere from the inside (and rotate to make its legs always face the walls)... it's been driving me nuts
CustomEditor
@steady moat @leaden ice Thank you and I'll give it a read
quick question why is cube.transform.position
not accepting Vector3 box_location = new Vector3(0,3.38,0);
Argument 2: cannot convert from 'double' to 'float'
sounds fine. show the assignment.
perhaps you are attempting to do this outside of a method
because 3.38 is not a float value
ah, yes, that will slow you down.
h o w
because it is a double
which you should be reading
okay doky
rather than just seeing an error and stopping
then learn how to write float constants
i came from unreal + houdini
sorry
then you need to learn to write C#, yes
you will be writing a lot of float literals
(a "literal" being anything that literally has a value)
"hello", 123, 40.0f, ...
The docs for BuildPipeline.BuildPlayer mention a problem with domain reloading
... the built-in scripting symbols defined for the current active target platform (such as UNITY_STANDALONE_WIN, or UNITY_ANDROID) remain in place even if you try to build for a different target platform, which can result in the wrong code being compiled into your build.
if i understand correctly, this means that if i try to build a dedicated linux server build via code, it won't have the correct defines set
is there a way around this or do i just need to switch the build platform every time?
you can write your own build script
is C# and extention of C or just inspired by it ?
Sounds like something you should input into a search engine.
And numbers with decimal point are treated as double by C# by default if there's still confusion, you have to tell it that it is a float specifically..
I am talking about a build script actually
Bit of interesting history to C# and iirc, it was developed to be a competitor to Java, but the rest yeh, google is best ^^
!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.
my player health code: https://gdl.space/eyikiduvof.cs
my AI enemy code(shorter version): https://gdl.space/rehahejibe.cpp
on my AI enemy code I'm getting an error on line 40: Object reference not set to an instance of an object
I searched up this error and unity is saying that the component in my game on that line of code doesn't exist, but it in fact does.So, I was wondering If anyone could see what I'm doing wrong.
playerhealth is null, did you set a value in the inspector?
Yes, I've set it to 100
no, playerhealth is a class not an int
my reference to my script is playerHealth and inside that script playerHealth is a public float
but your reference is null
it will still be null unless playerhealth is on the same game object
oh yea, so I would set it to the object that holds my playerHealth script
correct?
yes, leave playerhealh public, fill it in the inspector and remove the getcomponent from your script
I still get the same error
is it because my player holder is an empty transform
does that matter?
show latest code and screenshot inspector for gameobject with BananaBoy
it has to be a gameobject thats my mistake
player health: https://gdl.space/yonapofequ.cs
Banana Boy: https://gdl.space/ixumukujix.cpp
that wasnt the problem
you did not remove the GetComponent like I said
ok it works
I dont need GetComponent because their not on the same object
sorry ab that
no, you dont need GetComponent if the reference is filled in the Inspector
in this case you are overriding the inspector reference with null
yea, but for my other scripts I never referenced it in the inspector and just used GetComponent because their on the same object.
is that not why it worked with my other scripts?
yes, it is
Hello!
I've been trying to add a rotating rigidbody (with the ability to move) as a sort of joint for another rigidbody, with a script that rotates said joint, but for some reason, the joint also moves with its arm
why is this?
the script is only set to rotate the joint, not let it omve
You need to use actual joints for connected rigidbodies. https://docs.unity3d.com/Manual/Joints.html
i do
im using a distancejoint2d
and the joint is attached to a hinge joint 2d on a parent
If you don't want for forces to propagate to another rigidbody, set limitations.
how would one do this?
i'm very new to joitns
*joints
can't even spell lol
wait
ok
good news: I got it working
bad news: The joints don't move with moveposition();
You can make it kinematic or set constraints https://docs.unity3d.com/Manual/class-Rigidbody2D.html
Move position is not a physics method to move things. It just updates rigidibody position
Guys, I heard that we could make camera shaking with coding C#. Not game playing camera shake. I meant its normal shaking like you have watched some short film that when FPS walking, idle-ing, etc. like camera shaking in cinematic film
Or I want the code from github
or is there any tutorial of it
are there better movement methods?
Use #π₯βcinemachine has that stuff available
If you are using physics enabled objects you should use add force methods
it seem C# as hard as C++
is C# performance equivalent to C++ i read that its not
c++ is the most difficult language (apart from those non-human readable language)
or the difficulty you are talking about is something like "writing a compiler in c# is difficult", "writing a browser in c# is difficult" ...
C# may not be a fast as C/C++ but it's very performant and will handle most tasks such as game development with Unity and even scalable backend services with lots of requests
ohhhhhhhh i seeeee
is C# corss platform like you can devleop an app in C# and ship it to multiable OS like C++
C#/.NET along with Java is industry standard for large enterprise application such as banking/finance software
This one is a bit tricky. C# is largely built for Windows but with the new .NET Core environment, C# can now run cross-platform, it's not completely cross-platform in the same sense as Java but it is moving in that direction with the modern .NET framework
so if i wanna write a multi platform app i need .NET
forces are hard to control tho
i want something easier to control
well can .NET run on android ?
So I will say that you can write cross-platform, you can also leverage UI frameworks such as Avalonia (cross-platform WPF/XAML) and Xamarin for mobile applicatiopns
Yes, Unity projects can be ported to Android/iOS and you have Xamarin that can be used for cross-platform development. There is also something called "Platform Uno" that allows you to share a single codebase across many platforms
You can also use ASP.NET applications and create web-based applications that will obviously be cross-platform as well
just trying to understand the eco system of each language
You are not providing enough information to what exactly you are trying to achieve and this is not a code question. Ask in #archived-game-design a full question to figure out what kind of controll you want to have or ask in #βοΈβphysics how precicely to control physics interactions.
For my world Generation the chunks have some black edges around 2 of the sides.
I don't know what is causing it and it makes the chunks stick out too much. I know it is not shadows, the uvs and the lighting. I don't think it is the normals or the vertices but it might be.
are you sure its not the lighting, because that is the exact appearance I would expect if all of the mesh' faces were part of a single smoothing group and that side of the mesh is not subject to directional light
Architecture(?) question - what is the most sensible and flexible way to write/manipulate a large array of Vec3 values? (And doesn't necessarily have to be Vec3 values if there's something smarter.)
XY Use case would be: picture any '3D graph mesh', the end goal I am seeking to support is ease of applying arbitrary transformations to the positions to the entire thing
thoughts that come to mind are a texture height map, or a greatly subdivided mesh, but I don't know how you'd then pass the arbitrary deformations into such a thing
Ideally it needs to support translation of XYZ coordinates per position, and if possible support being able to grab and scale any part of the array, or deform it. IRL example - support grabbing and manipulating a piece of cloth in a square-ish frame
yee, this is in game with no light at all
Hm yeah no directional light there. I assume its also an unlit shader even though there's no light in the scene?
great observation. The material was lit. I changed it to an unlit now and then it works with light on so i think i will keep it like that
anyRectTransform.position
This isn't really enough information. First off - the coordinate space of the RectTransform changes depending on the Canvas' Render Mode.
Second - if it's NOT a world space point you are passing in, you will of course get a nonsense answer here
if I use the .position value of any RectTransform I should get its world position iirc
No. In Screen Space Overlay it will give you a completely separate coordinate space
Can you explain what you are trying to do here?
because that's how overlay works
it doesn't exist in the world
it's just overlaid on the screen
^
Sounds like you're just doing something wrong
I'd figure out what that is and fix that
rather than try to recreate this built in behavior yourself
Have you familiarized yourself with all the anchoring/pivot etc concepts here?
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIBasicLayout.html
Is there a way to tell if an asset reference changed in the editor between the last time the scene was open/when the scene is open?
Like if I renamed a prefab/scene and wanted to change serialized variables on my component.
I want to make a randomized grid-based game. In my code i have generated a matrix of 1's and 0''s that represents the map i want. Would it be sensible to, at runtime, generate TileMap each time? It feels weird because when making the game it means i have 0 use for the unity visual UI, and as the camera pans around idk if it would slow down or if id need to make my own hack for "resetting" the grid and re-tecturing on the fly to make it look larger. It just feels like im doing it wrong
yes, you can use guid to get the reference to the assets, so renaming would not affect the reference to the assets
https://docs.unity3d.com/ScriptReference/AssetDatabase.GUIDToAssetPath.html
https://docs.unity3d.com/ScriptReference/AssetDatabase.AssetPathToGUID.html
https://docs.unity3d.com/ScriptReference/AssetDatabase.GUIDFromAssetPath.html
i guess you could remember the path and act if it changes
since the GUID doesn't change
Ah perfect. I can just use the GUID then and not worry about the name.
I am assuming moving an asset outside of the editor could break the GUID though(not worried about this as that already is a bad practice).
If you don't move the .meta file along with it, yes.
Wait, SceneManager has no way of getting scene by ID, is there a way to get the asset instance by ID durring runtime? I am assigning SceneAsset in editor(but that is editor only) so I am saving the data needed to get the scene info durring runtime from the SceneAsset.
.scene is part of Unity asset
those api linked above will work
oh runtime... then that's another story
Indeed
ideally you'd want to do this in edit-mode tho
So the workflow I have right now is. Add scene load component -> select the SceneAsset for the scene you want to load in editor -> this saves the data needed to load the scene during runtime. The problem is if I grab scene name in editor it wont update from a value change on the SceneAsset, if the scene name is changed it won't get updated in my script. So I am assuming I will use the links above to pull the info from the AssetDatabase at run time based off of the AssetID I get from The SceneAsset.
edited*
assuming AssetDatabase is not Editor only
bad news for you
I mean, this whole thing can be made much simpler by accessing the indexer to change scene, no ?
what do you mean by indexer?
I am unfamiliar with this I think
Like the Scene build number?
yes
tho that can go south pretty easily if you removed one of the scene then the buildIndex willl change too
I am assuming I would run into the same issue as using the name, if the order of scenes is changed, my in scene component's values won't be updated.
Yeah
I am looking into adressables also, which seems to be the only way forward so far.
I mean I could also use scriptable objects, but π
An asset to reference an asset is clumsy at best.
I mean getting all scenes is as simple as π
var scene = SceneManager.sceneCountInBuildSettings;
string[] arr;
arr = new string[scene];
for (int i = 0; i < scene; i++)
{
arr *= Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i));*
}
so you can do your own logic or a way to update your component or whatever
this is more like xy problem to me
Yeah getting scenes isn't the issue. I am trying to build a component that doesn't break on scene asset changes, while also not hardcoding the desired scene identification.
As using user input ID or name will break on changes, where an asset/addressable reference won't break on changes.
I mean not sure addressables will do what I want yet, as it is pretty expansive and I am still studying it
The unity hub, go to installs and then press instal editor. The newest for each release will be shown under the tabs. Also not a code question
Not sure, but also not the best place to be asking this.
Something under Graphics
For unity LTS is the newest long term support version, otherwie Alpha is the "newest"
Take the latest LTS, it's the one that has the long term support (what LTS means). It's ordered by date, so the greater the date, the latest it is
Also not a code question so it doesn't belong in this channel
-Edit- I moved my question to #βοΈβeditor-extensions
Why am i getting this errors? I did something wrong? Its Netcode for GameObjects
The error is telling you what's wrong
i still dont understand what it wants from me
"RPC parameter types must implement INetworkSerializable"
How do I create a vector that is 45 degrees away from a point
Do your parameter types implement either of those mentioned interfaces or not?
Degrees are a measure of angles not distances, can you be more specific?
A point is a position
To have an angle you need two directions
Like this
So what's the "point" in this image and around which axis do you want to rotate
Basically you need more information than just a "point"
Yes I know
are you asking about a point on a plane?
Wait I shall clarify further
These stairs spawn repeatedly following the up direction:
{
Vector3 spawnDirection = Vector3.up;
for(int i = 0; i < maxStairsSpawned; i++)
{
Instantiate(stairPrefab, startPos.position + spawnDirection * i * padding, Quaternion.identity);
}
}
This is the script
I want the spawnDirection to be this vector
so you want a vector that points up and forwards
you can just punch in whatever vector you want
Vector3.forward + Vector3.up, for example
An angle alone is not enough information. There are many vectors that are 45 degrees from the up-vector
the steepness is one thing
the other thing is which fricken direction do you want
if you want to say "both are variables" that's fine
it's enough to say there's a variable for that provided
if you want the staircase to go forwards with a varying steepness, then the math is pretty simple
Quaternion.AngleAxis(angle, Vector3.right) * Vector3.forward
a positive angle might send that into the ground
i forget which way it rotates
I actually did this a while back but I deleted the folder by mistake and... forgot how:
#archived-works-in-progress message
hmm alright
i think rotations are counter-clockwise?
if not, then use Vector3.left or negate the angle
wait, but this would only work right if they were clockwise

ah, there you go: angle axis
although I don't understand why you're rotating around Vector3.forward
you probably want to rotate around the right vector in the local space of the staircase
here
using Vector3.right or Vector3.forward will make the behavior depend on which way you're facing
Alright
I'm making a 2D top down zombie game, I need some AI pathtracing for the zombie AI. I've tried using the A* Pathfinding Project and it works well but conflicts with my knockback system. Is it worth me writing my own A* pathfinding algorithm? I don't know how much work it would be.
no, you just need to stop the A* system from updating positions while knockback is happening
or, you need to manually correct the position it's using
haha literally just tried this, but yeah it works, thank you
just a simple bool toggle
that saves me a lot of work
I haven't used the A* addon, but with the unity NavMesh system, you can directly set the agent's simulated position
I'm guessing something similar is possible
that was my earlier approach, but the agent would teleport whereas my initial knockback implementation was gradual
i guess i could do it frame by frame but this method works fine now
ye
you can just update the simulated position when turning the navigation back on
(it might already do that)
Is it appropriate to create a new instance inside the resource field of a using statement?
using (MyWriter writer1 = new MyWriter())
{
writer1.Write(this);
}```
Traditionally it's not created through a new keyword, but from somewhere else like this
using (StreamReader numbersFile = File.OpenText("numbers.txt"), wordsFile = File.OpenText("words.txt"))
{
// Process both files
}```
It can be done however you want
the only important thing is that the left hand side of the assignment is an IDisposable which you want to be disposed at the end of the scope.
Thank you
there's no real difference between using a constructor and using a method
the method probably calls a constructor anyway
at some level every object created in C# has its constructor called
A static function like File.OpenText is just running the constructor on your behalf
It's totally legal to create the object earlier and use an existing reference in the using statement
There doesn't need to be an assignment
Example from C# docs:
StreamReader reader = File.OpenText(filePath);
using (reader)
{
// Process file content
}```
also in newer C# versions you can just do:
using MyWriter writer1 = new MyWriter();
writer1.Write(this);
That's what I was thinking. Then the IDisposable dispose would destroy/cleanup things, but in this case the writer does not have any member variables
the fact of it having or not having member variables isn't really relevant
and that's not related to the presence of parameters in the constructor either
The things you might want to clean up aren't always member variables either
For Dispose wouldn't it be relevant so that you can call destructors on those managed member objects?
you don't ever need to call a destructor on a managed object
Unless you mean they are also IDisposables
and you mean to call Dispose)(
but no, the object could for example delegate to some other static reference to actually hold references to the things it needs to clean up
Yeah if the managed objects are also disposables
Guys how do I use an animation curve to interpolate between a starting size and an end size
I want to create a pop up effect
If you have nothing to dispose there's no reason to be an IDisposable. But there's no limitation on what can be the disposable bits that need cleaning up
Well ill ask here after spending some time reading the api, In unreal we used to have a path for the texture (or the file) you wanna import
and a path inside the engine content folder, in unity only take one path AssetDatabase.ImportAsset
Use it just like Lerp but instead of calling Lerp you call myCurve.Evaluate(t)
do i have to do a bash script that would throw files/textures inside of unity project folder
before improting them
How would I find t
I want the animation to last x seconds
count up
t is the time through the curve you want
just...let unity import the assets
0 being the start, 1 being the end
animation curve.Evaluate() method. Here's a sample that rotates over time, you'd want to use transform scale possibly instead
IEnumerator Lerp(float afEndValue)
{
float animationTime = 0;
while (animationTime < _animationDuration)
{
_valueToLerp = Mathf.Lerp(_startValue, afEndValue, _animationCurve.Evaluate(animationTime / _animationDuration));
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(new Vector3(0, _valueToLerp, 0)), 179);
animationTime += Time.deltaTime;
yield return null;
}
_valueToLerp = afEndValue;
}```
{
Vector3 originalSize = gameObject.transform.localScale;
gameObject.transform.localScale = Vector3.zero;
float time = 0;
while(true)
{
time = Mathf.MoveTowards(currentTime, timePopping, popUpSpeed * Time.deltaTime);
gameObject.transform.localScale = Vector3.Lerp(Vector3.zero, originalSize, curve.Evaluate(time));
yield return null;
}
What's wrong with my code here
For some reason when I print time it keeps fluttering instead of just going to one
ohh
my guess is you're starting it in Update
No I'm starting in start
time = Mathf.MoveTowards(currentTime, timePopping, popUpSpeed * Time.deltaTime);
here
oh wait also your MoveTowrads is not using time as the first param
yep
Hi guys i want to create a game with random event like RPG Game and i want some tips to make it easy like scriptable object or something like that someone can help me pls ?
Quick question, but what the heck happened to the lighting? anyone can help me?
ignore the main menu
i think lighting
wait this is the wrong channel
i thought this was #π»βcode-beginner
also i didnt know there was these channels
imma ask this question there, thanks.
could anyone help me figure out why my uvs might not be working correctly?
if theres a better channel to ask it in just lmk :]
go ahead ig
not a code problem. probably see #πβart-asset-workflow
yeah
i think it's to do with my code π
the texture is fine im pretty sure, im just struggling to get it mapped to the mesh correctly
then ask your question and show your code.
so basically i have a procedurally generated voxel mesh and just a little function that loops through every voxel and adds the uvs to it (based on a UV lookup table)
void AddUVs() {
for (int i=0; i<24; i++)
uvs.Add(uvLookup[i])
}
that code works and gets the uvs mapped nicely but in reality i need to give each face a different texture based on what face it's on, for each voxel i have a list of the visible faces (i.e. the faces that don't have another voxel right next to them), and i wrote this code to try and work with this new solution
void AddUVs(List<Vector3> visibleFaces) {
for (int i = 0; i < 6; i++) {
if (visibleFaces.Contains(offsets[i]))
{
switch (i) {
case 0: // y- face
uvs.Add(uvLookup[0]);
uvs.Add(uvLookup[1]);
uvs.Add(uvLookup[2]);
uvs.Add(uvLookup[3]);
break;
case 1: // y+ face
uvs.Add(uvLookup[4]);
uvs.Add(uvLookup[5]);
uvs.Add(uvLookup[6]);
uvs.Add(uvLookup[7]);
break;
case 2: // x- face
uvs.Add(uvLookup[8]);
uvs.Add(uvLookup[9]);
uvs.Add(uvLookup[10]);
uvs.Add(uvLookup[11]);
break;
case 3: // x+ face
uvs.Add(uvLookup[12]);
uvs.Add(uvLookup[13]);
uvs.Add(uvLookup[14]);
uvs.Add(uvLookup[15]);
break;
case 4: // z- face
uvs.Add(uvLookup[16]);
uvs.Add(uvLookup[17]);
uvs.Add(uvLookup[18]);
uvs.Add(uvLookup[19]);
break;
case 5: // z+ face
uvs.Add(uvLookup[20]);
uvs.Add(uvLookup[21]);
uvs.Add(uvLookup[22]);
uvs.Add(uvLookup[23]);
break;
}
}
else {
for (int k = 0; k < 4; k++)
uvs.Add(uvLookup[0]);
}
}
}
the else clause at the end is because i need to have 24 uvs per voxel regardless
obviously after i get this working ill add in the code to actually work with each face independently but right now, this function should produce the exact same result as the old function but it isn't, can anyone help me figure out why?
been bothering me for the past few days sdfjkhsfdh
in what way does the output differ?
yee one sec i can grab a screenshot
this is the output from the first function
and this it the output from the second function
the first function also works with the breaking/placing blocks code, but when you try and break/place blocks in the second one, the blocks are removed/added correctly but the uvs get added incorrectly
like for example this
are you sure that VisibleFaces isn't just wrong
you can throw in || true to make the if statement always run
visibleFaces is used elsewhere in the code and works so i dont think so, but ill give it a shot
ah
interesting...
Perhaps you have the order of the faces wrong in your new UV function, then.
That would explain why the top row showed up
i might know what it is, ill try
that was not it
i think you're correctly setting face visibility
but I think you have the wrong order in this method
it works if i add the || true though?
yes, because that skips the visible face check
so it always assigns the UVs
but it looks like every side of the object has the same texture on it right now, so you can't really tell...
oh the visible faces?
I think you have the switch cases out of order.
The visible faces are clearly right, since the cubes are rendering correctly.
sorry im quite new to unity and even more so to uv stuff, why would the order of the switch case result in this?
if i changed the order would it not just change the orientation of the faces
well, clearly the order that you set the UV coordinates matters
your code says it's doing -Y, then +Y, then -X, ...
I think your order is wrong.
I'm not talking about the order within each case
I'm talking about the order of the cases.
everything is in the same order im pretty sure except for the offsets
im not sure why but when i put the offsets in the same order as everything else
it results in this
Is there a way to load a scene by GUID? I was looking into Addressables, but how they are resolving the GUID to asset is hidden behind AddressablesImpl.LoadSceneAsync and haven't been able to look at the source.
Does RuntimeHelpers.RunClassConstructor works in AOT platforms?
Hello, I have a small problem.
First, a bit of context.
It's about object pooling for bullets and how to handle them effectively.
I have a "Bullet" script that essentially tells the bullet to return to the pool when it goes outside the camera's field of view.
Since it's a shoot 'em up game, I have some doubts about this system.
Would it be more sensible for the camera to take over the object pooling? By saying that when a bullet leaves the camera's view, throw it back into the pool.
But on the other side im more flexible with the bullet script since i can extend the pooling conditions for each bullet ..
the bullet can check if the camera can see it
yea thats the way i have it now
Can I generate sprites from spritesheets at runtime without using the UnityEditor namespace, or is that still a required thing?
nevermind, that was suprisingly easy to look up
help raycasting ui object
use the event system
this is what ive got so far but it doesnt detect anything
Vector2 screenCenter = new Vector2(Screen.width / 2f, Screen.height / 2f);
// Perform a raycast from the center of the camera
Ray ray = mainCamera.ScreenPointToRay(screenCenter);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1f);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
// Check if the hit object is on a UI canvas
// UI object is hit, do something
Debug.Log("here3 ");
}
Debug.Log("here2 ");```
UI elements don't have colliders
Physics.Raycast only works on colliders
do noy use Physics.Raycast
use the event system
how do you do that
depends what you want to do
i just want to get the gamobject over the centre of the screen
Is your cursor locked? It's unclear why a UI element would be in the center of the screen
and why you wouldn't know if it is
what kind of game is this
so you actually want to know if the pointer is over a UI element
you really shouldn't use UI for an OSU trainer
use 2D sprites
you're making a classic mistake
don't make your game out of UI
UI is not for gameplay
and use Physics2D.GetRayIntersection to detect 2D colliders from a screen ray
thank you
And sprite renderer?
I have an array called LevelData.entities and i wish to store a reference to Player which is an entity stored in that array. Do i use a pointer here? Im worried that i make a reference to the player-object in the array then when i clear out the array it wont delete the Player since they still have a reference
C# has no pointers. C# has references
is not possible
can i make a "soft reference" that turns null if it is the only one?
it's possible it's just the wrong way to make your game
Well, your mouse is raycast
You could use https://learn.microsoft.com/en-us/dotnet/api/system.weakreference?view=net-7.0 I guess - but why?
please dont backseat drive my game i have autism and dont like talking about it cause i get embarassed so i just made up a game ideaa
You use mouse for buttons or sliders
well, get rid of the reference, then
i just need to raycast the centre of the ui
You asked for advice, so advice is being given. There's no need to get upset about it. If you don't like it you can build the game however you want but don't expect it to be easy or for people to be able to help you
What is going to happen is "Note to self, clear this reference" then 2 months from now i will go "why tf is there a memory leak?"
If you want someone to fix your car, you should probably tell them what kind of car it is and what's wrong with it. It's not my problem if you can't handle simple clarifying questions.
why do you have the reference in the first place?
Bye
i.e. why do you need that reference and to have the player in the array?
Let me handle this from here
if you dont know how to do it then ur probably also unaware of the better solutions. If i asked how to launch a thread to query a website i probably dont know that you can use a coroutine
be my guest
please please please i just want to know how to raycast ui
yall dont understand im trying to prototype in the easiest convenience
ive never used unity 2d before
but i understand the ui system
bc if i want to have the camera follow the player i will need to do a foreach loop to find the player each turn.
If i keep the player totally separate, then every subsystem such as pathfinding will need to account for this singular exception
thanks for wasting my time like yall waste your time using an outdated game engine
you arent paying us you are requesting information and volunteers are helping you. You cant really complain about how the volunteer spends their personal time answering your question
is the player getting destroyed when the array is cleared?
go ask chatgpt then
let us know when your attitude has improved
perhaps we can help you then
i dont have 4 i only have 3 . 5 which is trash
We are real people, taking real time out of our day to help you. Your behavior is unacceptable.
bruh stingy comments = bad
Bruh
one comment slightly stingy = BADDDD
ok i concede defeat
i will build it in 2d
ok ok
Theoretically, yes. For example, when you go to the next level, id wish to dump all the entities in the array into a file to save that game. I would then wipe it, and put the player on the next stairs
OH WAIT nvm their position wouldnt change so no need
What is not outdated engine?
@digital hemlock
@hard tapir No need to rehash this
{
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = new Vector2(Screen.width / 2f, Screen.height / 2f);
List<RaycastResult> results = new List<RaycastResult>();
GetComponent<GraphicRaycaster>().Raycast(eventData, results);
foreach (RaycastResult result in results)
{
Debug.Log("Hit UI element: " + result.gameObject.name);
}
}
godot because its free and under mit liscence, and unreal because it has better tech
Okay π
Remember to put using UnityEngine.UI
@digital hemlock There's no off-topic here. Enough with this already.
yes, there is a GraphicRaycaster
sorry
...
@hard tapir Stop with provocations
Actually to be honest, it's not about engine but it's about you
All engines has their cons and pros
does this work with ui @hard tapir ?
that is the point of the GraphicRaycaster, yes
The engine uses it to decide what you're clicking on
Yes
It should work
i have the raycasting function running in the update
do you need to put the script on the camera?
Yes sirπ«‘
i get an error on this line GetComponent<GraphicRaycaster>().Raycast(eventData, results);
NullReferenceException: Object reference not set to an instance of an object
You should ask it in #βοΈβeditor-extensions
You need to reference it
Go into canvas, then add gtaphic raycaster component
ok sweet
I apologize, I'll move with my question here. Thanks!
@sleek bough do you agree?
public GraphicRaycaster rc;
Yes
No!
Or serialize field private
Well, if it's attached then no need
No problem
If it wasn't attached you wouldn't be able to drag-drop into a field, I don't get you here
My point was that, because the code used GetComponent<>(), no need to create a field and drag-drop
You can have that script on empty gameobject then reference that from canvas component
Yeah but the script you provided, and you probably didn't read is meant to be on the same object as the Event System and the Graphic Raycaster
But if it's attached on that canvas with graphic raycaster then indeed, toi don't need to
Yes
My mistake
So those two components should be there on that game object
Yes
Hey there guys, is it there any way to modify/reimport a mesh/asset after building the project?
Modify the asset, reimport, rebuild the game
i believe you'll have to rebuild unfortunately :(
Hmm, so I'm looking at https://forum.unity.com/threads/materials-clone.484503/
I want to create a new instance of a material for a bunch of instantiated objects at startup, but then update properties in those materials Update() without creating new objects
doing myObject.GetComponent<MeshRenderer>().material.SetFloat(...); does indeed seem to make a copy (which is good, since I can't call new Material() in udon, and this is a VRChat world)
if I just keep a reference to myObject.GetComponent<MeshRenderer>().material and call SetFloat() on it later, would that update without a new copy? I don't see why it would be any different...
perhaps I should be using this: https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
I'm trying to get the cursor so it can't go too far away from the player, I want to give the cursor a radius it can move around the player kind of like in getting over it if that makes sense
sounds like you may need to conceptually separate what the cursor means - you have your actual cursor, which is your mouse position say, and you have an in-game object that points to a location between your character and cursor
don't think of it as "locking the cursor to a radius"
yeah, that would probably annoy the user
and you don't want to annoy me
i complain very loudly
whats the best way to basically just render a 2d array of colors to the screen
i want to make a game similar to Niota and I'm trying to render the elements to the screen
Make a Texture, render itt with RawImage
You can then modify the texture either with a compute shader or just in C# code
Anyone know why my raycast works in the editor but not in a built instance?
What is the idea behind Gui Cameras?
Not without seeing your code etc.
{
if (Input.GetMouseButtonUp(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 9999.0f))
{
if (hit.transform.gameObject.GetComponent<Hero>())
{
Hero hero = hit.transform.gameObject.GetComponent<Hero>();
uiHandler.EnterMovementMode();
uiHandler.selectedUnit = hit.transform.gameObject;
}
else
{
image.SetActive(true);
return;
}
}
}
}```
the image.SetActive(true) is just for debugging in steam
You can just use Debug.Log
how do u access logs from a steam instance?
It won't
Your issue is probably due to script execution order issues or framerate differences or something along those lines
You need to add logs and question your assumptions
E.g. make sure the code is running as expected and there's no errors etc
alright thanks
Can anyone here recommend a course on best practices in coding GUI?
I have not much idea in how to tackle that. I know how to do basic ui stuff, but not really an idea of how to do it well.
π 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.
It's not really that different from regular unity programming
does AssetDatabase.RemoveObjectFromAsset automatically call AssetDatabase.DeleteAsset? or will not deleting them cause a leak
it does not (to my knowledge) call DeleteAsset because you're removing an Objectβit's not guaranteed to be an asset. just make sure you call SaveAssets afterwards . . .
oh i see
i was having some trouble calling deleteasset myself
so i just called saveassets ye @rain minnow
yep . . .
hi,
how can i distinguish between click events from UI TOOLKIT Element and click event when the user only click within the screen area?
when the user click button ui element i receive click events from both ui element and screen click.however, i receive one click event when the user is click within the screen area only.
I'm using unity new input system and ui toolkit.
help please
Is there any sort of different preferred naming system for async tasks akin to coroutines?
IEnumerator C_ExampleCoroutine() { ... }
async Task ExampleTask() { ... }```
ChatGPT is giving me this? What do ye think?
async Task ExampleTaskAsync() { ... }```
@swift falcon ask whoever is going to read it in future
Just me then I guess. Has anyone else seen appending -Async before or did the AI make that up though?
I'm very new to multithreading btw
if you're solo you can just do whatever. i don't name my coroutines like that and i never had any problems π€·ββοΈ
It's some convention for methods marked as async, postfix them with Async, so they can be differentiated from sync methods
toggle a bool on hover, and don't register background clicks if true?
https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.MouseOverEvent.html
anyone have a solution?
when I click the play button it goes straight out of the editor. from yesterday it was safe, there were no problems until noon. then when it was a bit late this afternoon it appeared on all the projects
thx! i'll try this
The second log suggests that you should only have one event system in the scene.
If that does not solve it, restart your computer. Still nothing? Ask in #π»βunity-talk as it's not a code question
thanks, i will try it
The third and fourth errors are both from a network problem
I'm having this issue where if create or delete a script, Visual Studio opens itself and reloads everything. This is kind of annoying, take a look.
https://cdn.discordapp.com/attachments/786969998363066381/1121499694879740146/2023-06-22_20-57-48.mp4
are you hitting enter twice or something?
nope
ah right, you clicked Delete
That's a new one. Did you already follow the instructions to set up the !ide ?
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
yeah, i've done this
okay, so it's not like unity has some kind of default "annoy user" mode if you haven't configured this
i wonder if this is VS's fault
what happens if you delete a file (and its .meta file) without Unity being focused?
let's see
If that doesn't make anything happen, then it must Unity doing it
but I have no idea what would cause that
okay so i deleted the file and nothing happened, then i focused back to unity and it started loading and then visual studio opened
(deleted the file in file explorer)
can you show me the External Tools settings?
i wonder if the command is messed up
but that only runs when you actually ask it to open a file..
what version of unity is this?
2022.2.17
ah, nevermind; this only appears when using the Code editor
my only thought would be to try unchecking everything and seeing if the behavior changes at all
it doesn't make sense, but...
You should ask about this in #π»βunity-talk , since it's not really a coding problem
Describe your problem, don't just ask for help
Ask your question.
Okay, I just wanted to ask politely
I'm trying to find a code of range of weapon
do not cross-post, especially when you're just asking people to give you code
Don't cross-post #π»βcode-beginner
People told me it wasn't there
WTF WHERE IS IT?
They mean't you can't beg for code on this entire discord. Do as I asked and you might be able to get a helpful response: #π»βcode-beginner message
Nowhere, try writing it yourself.
I said i tried and failed
What do you mean by failed ?
What was not working ?
Then write what your issue is so that someone can help
Did you have compilation error ?
This is the code
RaycastHit hit;
if(Physics.Raycast(fpsCam.position + fpsCam.forward, fpsCam.forward, out hit, range))
{
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
its not working, i dont know why
Well then, what's your error?
Why are you doing position+forward as the starting point?
The weapon just fires normally
It's not at first
Are you expecting it to fire... abnormally?
No, I expect him to shoot at range
What does shoot at range mean
It is found in void Shoot()
First within the method
A weapon that fires bullets in sequence
You need to clearly explain what you are expecting to happen and what is actually happening
I suspect there's a language barrier issue here too unfortunately because from my perspective you're just kinda saying random stream of consciousness statements.
Please make a thread in #π»βcode-beginner
This is the code I put in, but the weapon just fires at a slow, steady rate instead of continuously
Yes i'm from europe i don't know english 100%
Whatβs the bulletspeed
Make a thread in #π»βcode-beginner please, and stop posting here
It determines the speed the ball is moving at the firing
Where do you call Shoot() from? (answer in the thread)
Stop.
i hate you π
- Is there a way to calculate font size for tmp so that it vertically fits in N world space units (NOT canvas space)?
Do you guys know how effective is a Singleton in unity? Should I use them or does it hit the performance hardly in the later periods?
specially in single player games, enemies has to reach the player object, which may be done by checking nearby objects or directly using a singleton
I don't want them to check the nearby objects and spend effort in that way
but not sure if singleton worths it
or as a third option I have to send a reference to enemy spawner and give the reference to the enemy
which sounds better than the two
singletons are not a performance concern
they do, however, add a design constraint: they're a singleton!
making something a singleton that should not be a singleton can create headaches down the line
imagine you have an inventory system, and you decide to make that a singleton, because only the player has an inventory
but then, later, you realize enemies should also have an inventory
now you have to fix everything that depends on being able to easily find that singleton
Hey, i am getting a text from a textAsset with textAsset.text but when i try textAsset.text.Split("\n\n") it doesn t work but i have (image) in my text file
bump
i want to detect if a game object or more are on a specific direction, but i want to detect them even if they're within a +5 or -5 degrees range from that direction... how do i do that
try \n\r or is it \r\n, one of the 2
omg thks it works
\r\n, if you can remember CRLF that might help
i put \n\r and it worked
Presumably that is because you have two in a row and removed the middle bit (\r\n\r\n => \r\n), which is a bad way of going about things
hmm what does that mean? i should do something on my text file?
You should remove the CRLF (\r\n) series of characters, not \n\r, which isn't a thing, it just happens to do produce the same outcome.
you need Environment.NewLine probably?
string[] lines = operationtext.Split(new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries);
oh what s this
my problem is just for the textFile
you have been talking about \r\n or smth like that, but I do believe that's a better solution
yes
yes, this is how to split lines
this method splits text file into lines
but why not Split("\n") to split lines?
beceause it works
I think it's better to do with Environment.Newline
what s different?
it handles difference newline sequences based of the platform
\r\n for non-Unix platforms, or \n for Unix platforms
some systems encode newlines as a carriage return and a newline. others do just a newline.
I guess the bigger question is: where is this text coming from?
why should it matter?
because that determines how the newlines will be encoded
yeah, that's why it can cause troubles with \n
note that you can probably just split on \n and then strip the resulting strings
the text is a textAsset in my unityProject
I wonder if that means the newline encoding will depend on platform (if you, say, use Git to version-control this)
so Environment.NewLine is a better solution
That's what I would reach for, yes.
is it a question?
this could malfunction if the game was built on Linux and then played on Windows. You'd have \n-encoded newlines on Linux, and then Environment.NewLine would be \r\n on Windows
\r\n means
a
b
for example?
that s horrible, i need a different code for every platform???
Welcome to the world
check this out
I didn't even KNOW about some of these newline sequences
no.
oh π¦
\r escapes sequence within strings
It does sound ike you could just slap the string with that method and then split it normally
\r is CR, or the carriage return character.
newlines are easy, just wait until you have to localise something
You see, once upon a time, we used teletypewriters instead of screens
string message = "Hello\rWorld";
Console.WriteLine(message);
// output: World
Literally just a typewriter controlled by a computer
CR would reset the carriage to the start. It's a horizontal reset.
\n is LF -- line feed. That would advance the paper.
So, to properly reset for a new line of text, you had to send a CR and a LF
Linux-y operating systems discarded this and just use a LF character.
Windows did not (thanks Steve!)
wait, that's Apple
thanks Bill!
If you want to be absolutely sure that it Just Works, this method will find everything that looks like a newline and standardize it.
guys I have been trying to detect if a game object is within 10 degrees from a direction... should i do multiple raycasts or what ?
by default, it uses Environment.NewLine
and for Android?
no raycasting is required. just compute the angle
why do they need it?
Vector3 toObject;
Vector3 forward;
float angle = Vector3.Angle(toObject, forward);
(obviously, those two variables must have values put in them)
that was fast
i know i can maybe just modify that and use always \n\r
what do you mean
i mean that you can just compute the angle. that's it.
Again, \n\r is not a thing.
get a vector to the object. get a vector in the direction of interest. compute the angle between them.
this would also not have carraige return characters in it..
what do you even want to achieve?
i want to detect the closest object to the raycast, so my ray cast might not hit the object on the first time
So this is not the case.
raycast caches the first object
Explain what you're trying to accomplish. I don't know what you want to do.
i have a level string for example the image here, and i wan t to split the 3 things
"split the 3 things" ??
I think you should just use properly structured data.
wait, why isn't it JSON?
i mean the first 4 lines then the single line and the other lines
why do you write this in .txt?
it s bad?
it is.
i dont know how to explain it, but it is like a correction system... the player will aim to an object among several using the gamepad stick, this is the direction... most likely it wont his the object so I want to correct it by making the raycast hit the closest game object if it's within like 10 degrees from the original raycast
it s an asset in unity
if you can't explain it, then you can't implement it.
But I think you've explained it sufficiently here.
you should use .json file for this
made a thread
ok i hope it works
@warm stratus https://pavcreations.com/json-advanced-parsing-in-unity/
heu just .json file or .json format? bc for what i wanna do in the future, it s much better to use what i did
.json file, of course
For what you wanna do? What do you wanna do and why is it better?
if you don't know what JSON is, I'm not sure you're in a position to say that your format is "much better"...
i will use json in this project but not for this
i guess i am probably wrong
be able to share levels
I wonder if it's much better, because everyone uses .json
i think you are right
yeah i think json is good for what i wanna do
oh no that will be pain π
thks for you help π
we all did this at some point, lol
i wrote a very bad text adventure engine in Java
using my own hand-rolled file format
++ you basically spoke about all my concerns. I have to get used to write my code without singletons indeed
Singletons are good, as long as they stay single
but for my example at least, it is not a very good idea
since there may be 2 or 3 players
I don't think to add that possibility though
but what if I do, I would need to rewrite as you said
You can still keep the "vibe" of singletons (what a phrase) by having a Player object that references the stuff that would normally be a straight-up singleton
of course, at that point, you're basically just doing...normal programming
but that's how you'd migrate from singletons to non-singletons
rather than a static field, you reference something specific
@muted schooner as long as you understand how singletons are going to fuck you up down the line, it's fine to use them until at least singleplayer works. and if you're aiming for multiplayer right away, then you'll know how it'll fuck you up right away π
ideally, you'll just replace the static reference with a field, and then figure out how to assign the right thing to that field at the start
need to manage the references carefully though, a beginner's spaghet can be worse than singleton
You can get away with a lot of stuff with multiplayer and singletons, assuming you've got a single character.
I will use singletons only for the basic and static things from now
that may be an item database
Took me a while to get my head around it, but a lot of character code you'd throw into singleton can be clientsided
i do that in my nioh ripoff
Each shrine (save point) is defined by a scriptable object. I load all of those objects from a Resources folder on startup
the save file lists the IDs of all of the save points you've made it to
yes pretty much makes sense in case the thing is static you are going to use singleton on
I've tied a bunch of my playable character data, which you'd only have one of at every point of my game, to singletons. I did think about enemies with inventories and such, but I've went a different way with it and just developed drop tables.
A lot of these concepts should be declared early on anyway. It's not like I'm going to say tomorrow I want to change it all again.
Enemies on the other hand do need independent data so the idea wouldn't work too well with them.
I try to make the player non-special
the only thing that is unique about the player character is that your keyboard tells it to do things
Yeah, I do try to make stuff reusable when I can, but like when an item drops the only person I want picking that item up is the player anyway.
So it makes sense to just use the singleton reference to add it to their specific inventory and be done with it. And, like I was saying before, a lot of this functionality can be client sided so it will work on multiplayer games with the assumption that everyone controls a single character.
Help
currentRadius = Mathf.Lerp(targetSizes[currentStep - 1] * startRadius, targetSizes[currentStep] * startRadius, t);
currentRadiusZone = Mathf.Lerp(targetSizes[currentStep - 1] * 1, targetSizes[currentStep] * 1, t);
startPosition = transform.position;
transform.position = Vector3.Lerp(startPosition, targetPosition, t);
targetZone.position = Vector3.Lerp(startPosition, targetPosition, t);``` Lerp of position is not relative to shrink of scale, currently it looks like it moves instantly to new position and then it starts shrinking
In your experience, whats the best way to serialize a Dictionary?
I'm trying to set up some crafting recipes with a material needed key and an int ammount value
flatten it to/from a list or array of key/value pairs before / after serialization/deserialization
@leaden ice you are indie or in AAA studio?
startPosition = transform.position; is not correct for a Lerp
you need to save the starting position from the beginning
Thanks!
Just an indie/hobbyist
Same here
Well, that starting position changes
the starting position is the starting position. The position of the object changes but it started somewhere
Oh, now I understand it
It should lerp between previous position and target position
hello, may i ask how to use lerp as I still have no clue how to do such
you can do the same with vectors
@civic geyser you don't understand what lerp is, or how to lerp over time correctly?
just replace mathf with vector3
ok and one more thing
lerping over time
i want a object to over time move to a set position
not just instantly move
aighty than
I have a general question, not about coding, i hope i'm right here, where can i activate unity collaborata in version 2022.3.3f1?
not right. this is a code channel
thanks
it's actually braindead simple if you actually understand what each part of it does
also collab has been deprecated and replaced with plastic SCM
plastic scm?
whats that?
i'll talk in talk channel
In that case can I use MoveTowards?
Here, will this work now? ```float t = (Time.time - shrinkStartTime) / shrinkDurations[currentStep];
currentRadius = Mathf.Lerp(targetSizes[currentStep - 1] * startRadius, targetSizes[currentStep] * startRadius, t);
currentRadiusZone = Mathf.Lerp(targetSizes[currentStep - 1] * 1, targetSizes[currentStep] * 1, t);
if (t < 1f)
{
Vector3 startPosition = transform.position;
float maxDistanceDelta = Vector3.Distance(startPosition, targetPosition) * t; // Calculate the maximum distance to move
// Move the object towards the target position
transform.position = Vector3.MoveTowards(startPosition, targetPosition, maxDistanceDelta);
// Move the targetZone towards the target position
targetZone.position = Vector3.MoveTowards(startPosition, targetPosition, maxDistanceDelta);
}
else
{
transform.position = targetPosition;
targetZone.position = targetPosition;
}
a script is its own class type
but that doesent work with unity netcode
but is there an alternative ?
What are you tryng to do though? Passing your class on an RPC?