#archived-code-general
1 messages ยท Page 336 of 1
theres a slight stop before the loop is looped. That's what im tryna get rid of. I'll propably have to just make a new, better and longer song, and not switch and loop two 33 second clips.
or find the specific point you want to loop from directly by using the Time on the audiosource, maybe if you seek back it helps the delay of switching clips
is the original even a perfect loop?
Varify urself ๐ (should be, i tried my best in FL studio to edit it that way...)
I'm also trying Invoke
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
audioSource.loop = false;
audioSource.clip = track1;
audioSource.Play();
Invoke("PlayLoop", track1.length);
}
// Update is called once per frame
void Update()
{
}
private void PlayLoop()
{
audioSource.Stop();
audioSource.loop = true;
audioSource.clip = track2;
audioSource.Play();
}
nope, and it's even worse with Stop().
I would've done something like this
float minToSwitchTrack = 0;
void Update()
{
if (!audioSource.isPlaying) return;
float remainingTime = audioSource.clip.length - audioSource.time;
if(remainingTime <= minToSwitchTrack)
{
Loop(); //or maybe add delay?
}
}```
I first tried to make this in WPF lamooo i may be good at writing code but aweful at decidions.
xaml nightmares
In general, I notice that Unity's built-in UnityEvent system seems to replace <Func> type in C# as UnityEvents are serializable and play nice with the inspector, while <Func> types seem to lack the same integration into the inspector but are supposed to behave similarly to UnityEvents.
Is this assessment correct?
UnityEvents are slightly more performative than native c# events which is my take away from a lot of it
https://www.jacksondunstan.com/articles/3335
Little dated but still applies. Ah, rather the argument is the gc which they are somewhat better at but once you start adding more listeners they become worse.
JacksonDunstan.com covers game programming
Yes similar. I wouldn't say replace, but more like used when you want to set up listeners in the editor instead of in code
Hey, I need to restructure a part of my project and move a bunch of scripts from Runtime to Editor assets and vice versa, is there any way to move those files without breaking references in the project and with moving to appropriate namespaces after the move?
This answers it pretty clearly. Many thanks!
Moving the files won't break serialized references, nor will changing the namespaces. The safest way to move them is from Unity's project window
what about moving them and renaming/fixing namespaces in Rider though?
You run the risk of the meta files not coming along
Move in Unity, then do rename in Rider
how can I get the world position of a UI element?
RectTransform.GetWorldCorners
I tried that, it doesn't seem to match for some reason
First image is the UI element I'm trying to get
The 2nd is where the object is actually being positioned (blue dot)
tmpro has its own bounding box including the rect
oh, I can't see that blue dot on my phone but im assuming it's the thing in the bottom left?
https://docs.unity3d.com/ScriptReference/RectTransformUtility.html
You've got this class too
@latent latch @leaden ice I actually got it, thanks!
I'm not sure why but it seems the value isn't update right at the start;
That is, in Start() I'm starting a coroutine, and the 1st thing I do is calculate that position and use it from here on now.
If on the other hand I keep calculating it again and again rather than use it from the start, it works.
And thanks ๐
I have a question. So I set a button up with a certain variable in its onClick listener. How do I read what variable is attached to the listener?
are you talking about the values you can fill in in the inspector? i don't think you can access those from code
Ok so... maybe im not thinking straight right now...
but... im pretty sure i didn't even do anything yet... why am i getting these errors!??
thank you very much
i was losing my mind
im laughing in sorrow upon realizing that was the issue for me freaking out for 10 minutes
imma get a drink..
why this dont work?
public void RemoveCharacter(Speaker character)
{
if(dataHolder.charactersOnScene.Contains(character.name))
{
Debug.Log("Se removio el jugador: " + character.name);
dataHolder.charactersOnScene.Remove(character.name);
}
}
the debug,log works
but the name isnt removed from the list
Log the collection before and after removal
ok wait
WTFFF
EWHFERIOHDSKJSDHAUVHSDAFIVH
I DID THAT AND
NOW IT WORKS??
WITH THE DEBUG.LOG???? XDD
that probably did nothing
bro wtf unity
but i was watching the debugger, and it didnt works and
i add the debug.log and now it works
ty bro i love you
okay, now remove the log statement and test it again
okok
IT DIDNT WORK XD
with the logs it works XDD
and now it didnt work
with the logs
bro 
wait maybe yes
yes it works with the logs XD
idk men
I bet something else is changing than just the logs you are adding/removing
nonono look
with the logs this happen
and it works
the error is because the list dont have any member to make the log
but the game works so i will try to remove the character with a for
the for didnt work
WITH THE LOG AFTER IT WORKS XD
but i have this error, but it dont affect to the game
i < dataHolder.charactersOnScene.Count
For example: if you've got ten players, you'd have indices 0 to 9.
Accessing the tenth element would be at index 9. Index 10 would be the eleventh element and throw an out-of-range exception.
What?
Big code vs small code?
Zooming out
Code obfuscators you mean?
var x=3.0f;var abc='abc';foreach(var a in b){};
Code compression?
Did you press the "make code smool" button ?
remove spacing and change font size to something smaller, you're welcome 
c# is a compiled language, so you finally have two "codebases" for your c# project (source and il)
should I just be creating a regular C# thread then?
I need to implement a dynamic scroll view, when I scroll down and reach the end of the scroll view I want to populate more items inside the scroll view, and again when I scroll downward and reach the end of the scroll view more items are populated inside the scroll view. so how can I implement this?
iirc you can get the position of the scroll
Which part do you struggle with specifically? You can spawn more based on the scroll bar's value
might be worth checking https://github.com/mopsicus/uis
ScrollView has vertical scroll bar which tracks scroll progress, you can use that value
@lean sail Basically, I am fetching data from the server inside the scroll view and I make some logic using the scroll view verticle position when it reaches its end I call the function to load more data.if(!isPopulateDown && content.parent.parent.GetComponent<ScrollRect>().verticalNormalizedPosition < 0.1f) { Debug.Log("here"); if(pageNo != totalpage) { isPopulateDown = true; pageNo++; nextp(); } }
this works sometimes but not efficiently
well if you are fetching it from somewhere, i think this is to be expected. Maybe try to precache more results to make it smoother but ultimately this is gonna be a trade off from how much you want to try grabbing at once. Like if you had 1000 elements cached, the user likely wont notice anything. Now the issue comes if the users internet speed cant handle it
sadly unity doesn't have a built in- virtualization component / function
I agree. preload the next chunk of data using a threshold that is a bit wider in range. Also keep in mind, that adding stuff to canvas does not update the rendering immediately. You might have to trigger forcelayout on the UI rect to get the scrollbar trigger the new size. Besides that, very nice design on your UI I gotta say! Good job, clean and smooth ๐
For user convenience, you can also show a preloading item, like those placeholder items you see these days on websites and apps, when content is not done loading, which will give you another more smooth transition
Virtual scroller is pretty easy to implement though, especially since you have known size for each row.
You definitely want to implement virtual scrolling if you expect your users to load hundreds of rows, your UI is going to lag to no tomorrow if all of them are loaded, but only ever tens are visible at once.
@plucky inlet I make the logic when verticalNormalizedPosition < 0.1f it fetch data but after load the data for sometimes verticalNormalizedPosition stays less than 0.1f so i get multiple calls of API
You should preload the data
then use a bool to know if its trying to load something currently
Because ui is falling behind in rendering. So when you add stuff, force update your slider scrollview
And as bawsi said. Use a state, do not let guesswork control your flow
which function I should use to force update scrollview @plucky inlet
Keywords, forceupdate ui unity layout
@plucky inlet @lean sail @rigid island Thanks! I put some conditions to API fetch data and everything works smoothly!
do consider actually unloading some of those if you expect users to go that far. as burrito said above, this will start to lag very badly and some sites even suffer from this
@bawasi Correct!
Yeh, textmeshproui creates meshes which will fail at a certain length
I can't get Rider to sync with unity. I set the logging to verbose and am getting these two errors repeatedly, but I don't know how to parse them >~>
I've also been getting this error on every domain reload, not sure if it's related
This is a new file, Rider isn't detecting the serialized field or marking the unity message
This is an old file that was parsed correctly before i was having this issue
Share !code properly. As well as errors
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The code isn't actually the issue here. I wanted to share how the syntax highlighting looked in rider, what the code does isn't important. The errors arent anywhere in my code, somewhere the rider extension is throwing an error, but i can't set breakpoints in there and I don't know how to diagnose the issue
People on mobile can't see the errors without downloading your files. Share them as code (uploading to a paste site if too big)
Ooh, fair
The first error, it says it's from RiderPlugin https://hastebin.com/share/azarawuqop.vbnet
The second error, it says it's from RiderPackageInterop https://hastebin.com/share/wudogezehe.vbnet
And the error i keep getting on domain reloads. This didn't require me to turn on verbose logging. https://hastebin.com/share/hofezijuke.vbnet
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I am on linux, I cannot use VS and vscode has no auto complete. I have been trying to setup vscode but it is so nerve wracking. What script editors are easy to setup with unity auto complete?
There's not much to setup for VS Code though.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
You can follow the link here.
I would suggest your problems stem from the fact you are using Linux without knowing how to use Linux
I use linux because that way I can avoid boring process of setting up or installing something I would struggle as a windows user. I am not willing to go back to windows just because this particular problem. That would mean backup everything and lose time to installing of windows OS. I have 2 unity projects as university assignments and I think I cannot afford that much time to backup everything, install windows again and install all the software manually. Is there some script editor except vs, vscode and rider? I know vscode is much better than monodevelop, but maybe monodevelop is easier to setup? I was trying to setup vscode auto completion for 2 days - lost my nerves and gave up already. Does monodevelop come with auto completion by default? If not, which script editors have that auto completion out of box and easy to setup?
if you struggle setting things up in windows why would you think Linux is an 'easier' platform. It, in general, requires much more knowledge and skill to use well
Can I ask some complex question about gizmos? ๐
I've made a script that takes an array of objects and calculate the average size, to draw a gizmo so the user can have an idea of the volume occupied, the problem is that I can't rotate it on the pivot point.
What I'm missing?
{
float averageHeight = CalculateAverageSizeY();
Vector3 gizmoPosition = transform.position + new Vector3(0, averageHeight / 2, 0);
Matrix4x4 cubeTransform = Matrix4x4.TRS(
transform.position,
transform.rotation,
Vector3.one
);
if (isSelected)
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = gizmoColor;
Gizmos.DrawCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
Gizmos.color = gizmoColor * 2;
Gizmos.DrawWireCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
}
else
{
Gizmos.matrix = cubeTransform;
Gizmos.color = gizmoColor;
Gizmos.DrawCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
Gizmos.color = gizmoColor * 2;
Gizmos.DrawWireCube(transform.worldToLocalMatrix.MultiplyPoint(gizmoPosition), DrawAverageSizeGizmo());
}
}```
{
float volumeSum = 0f;
foreach (GameObject obj in objects)
{
Vector3 objSize = obj.transform.lossyScale;
float objVolume = objSize.x * objSize.y * objSize.z;
volumeSum += objVolume;
}
averangeSize = volumeSum / objects.Length;
return averangeSize;
}
I think I'm placing the gizmo on the wrong position, but when the corrds are 0,0,0 looks fine.
What's the point of setting the Gizmos.matrix to localToWorld but then multiplying the point with worldToLocal?
Linux is cool because most of software is available through apt or snap (I use ubuntu) but some programs require much more patience when it comes to find commands needed for installation. However, I just look on the internet, find and try out commands, manage to install 99% of software I need. Once I have saved that set of bash commands to a bash script, I can install that complex program just by running the script. (Maybe this is oftopic for the channel, sorry if so, just to finish my thoughts). So basically on linux, most of programs are possible to install with single command(apt, snap)/or script. I also have wget so I can easily download apt unavailable software from internet in programmable way. (Sorry for going too much offtopic - channel should be about unity code)
@olive bobcat If you just set matrix to localToWorld and then use (0, 0, 0) as the position in DrawCube, it will draw on the transform.position
(Maybe I'm missing something here - just trying to make sense of it :p)
Because I was struggling on drawing the gizmo with his base at the pivot point, because the gizmo is drawn at the center by default...
At a certain point I was coding blinded, not even sure what I was doing, but it works... until I rotate it ๐
So is this part: new Vector3(0, averageHeight / 2, 0); the relative offset you want to draw the cube at?
Yes it is.
I think you want something like this?cs Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0); Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(gizmoPositionLocal, ...);
๐ค Let me test it ๐
No need to muiltiply the position with a matrix again, setting the Gizmos.matrix takes care of that
And it should rotate with the transform
YEEEA \o/
Thank you so much ๐ป
I was banging my head on the keyboard for hours ๐
Np ๐ You overcomplicated it a bit
{
float averageHeight = CalculateAverageSizeY();
//Vector3 gizmoPosition = transform.position + new Vector3(0, averageHeight / 2, 0);
Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0);
Matrix4x4 cubeTransform = Matrix4x4.TRS(
transform.position,
transform.rotation,
Vector3.one
);
if (isSelected)
{
Gizmos.matrix = transform.localToWorldMatrix;
}
else
{
Matrix4x4 _cubeTransform = Matrix4x4.TRS(
transform.position,
transform.rotation,
Vector3.one
);
Gizmos.matrix = cubeTransform;
}
Gizmos.color = gizmoColor;
Gizmos.DrawCube(gizmoPositionLocal, DrawAverageSizeGizmo());
Gizmos.color = gizmoColor * 2;
Gizmos.DrawWireCube(gizmoPositionLocal, DrawAverageSizeGizmo());
}```
And now it looks even better @hexed pecan thank you so much ๐๐
One more thing, what's the idea of changing the matrix to _cubeTransform?
The matrix you are making there seems identical to transform.localToWorldMatrix apart from the Vector3.one scale
Currently to me it looks like: If selected, use pos, rot and scale of the object. If not selected, use pos and rot of the object but a scale of one
If that's not the intention, you could just get rid of all this
Matrix4x4 cubeTransform = Matrix4x4.TRS(
transform.position,
transform.rotation,
Vector3.one
);
if (isSelected)
{
Gizmos.matrix = transform.localToWorldMatrix;
}
else
{
Matrix4x4 _cubeTransform = Matrix4x4.TRS(
transform.position,
transform.rotation,
Vector3.one
);
Gizmos.matrix = cubeTransform;
}
And just do Gizmos.matrix = transform.localToWorldMatrix;
umm even better..
private void OnDrawGizmos()
{
if (objects != null && objects.Length > 0)
{
CalculateAverageSize();
}
DrawGizmo();
}
private void OnDrawGizmosSelected()
{
DrawGizmo();
}
private void DrawGizmo()
{
float averageHeight = CalculateAverageSizeY();
Vector3 gizmoPositionLocal = new Vector3(0, averageHeight / 2, 0);
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = gizmoColor;
Gizmos.DrawCube(gizmoPositionLocal, DrawAverageSizeGizmo());
Gizmos.color = gizmoColor * 2;
Gizmos.DrawWireCube(gizmoPositionLocal, DrawAverageSizeGizmo());
}```
xD
There we go, get rid of that extra fluff
Amazing ^_^
So now everything is working also scale! ๐ฅณ
Here is the complete code: https://pastebin.com/rzuWvvNv
The idea is coming from the Skyrim Creation Kit, which it show a gizmo of random objects.
So you can take different object place it inside the array, and on start it will select just one.
The gizmo shows the average size, so it's important the the size is about the same for all of the prefabs, but for placing bottles, crates, and other props it's really useful ๐
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Thanks again ๐
Yes
Or just use UnityWebRequest
how do i add an image to a spriteRenderer via script? (asking here cause i dont wanna cut off a questing in code-beginner)
Yo guys i got a question
So im making an inventory system for my game and every item has this GrabableObject script. Now the weird part is i got two objects, a basic cube and a OBJ key. Now for some reason the script works completly fine on the Cube so when i press E the cube gets destroyed and goes to the inventory, however the key for some reason doesnt work at all. I got a Debug.Log in the main inventory script and it debugs if the GrabableObject script isnt detected and the weird part is when i click E on the Cube it is detected but when i click e on the key it doesnt. both got a Box Collider, both got the same script. I litreally have no idea what could be the cause.
GrabableObject script :
public class GrabableObject : MonoBehaviour
{
public int ObjectId;
public string Name;
public Sprite Icon;
public bool isItem = true;
Inventory inventory;
// Start is called before the first frame update
void Awake()
{
inventory = GameObject.Find("Human").GetComponent<Inventory>();
}
// Update is called once per frame
void Update()
{
}
public void DestroyItem()
{
Destroy(gameObject);
}
public void SpawnItem()
{
}
}
InventoryScript :
{
GrabableObject grabableObject;
public RawImage itemicon;
public Text itemname;
public bool isHoldingItem = false;
public int HoldingItemID = 0;
// Start is called before the first frame update
void Awake()
{
grabableObject = GameObject.Find("Item").GetComponent<GrabableObject>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("EClicked!");
RaycastEvent1();
}
}
public void UpdateItemDetials(string name, Sprite icon)
{
Debug.Log("UpdatedDetails");
itemname.text = name;
itemicon.texture = icon.texture;
}
public void PickUpItem()
{
Debug.Log("PickUpItem");
UpdateItemDetials(grabableObject.Name, grabableObject.Icon);
grabableObject.DestroyItem();
HoldingItemID = grabableObject.ObjectId;
isHoldingItem = true;
}
public void DropItem()
{
}
public void RaycastEvent1()
{
Debug.Log("RaycastSent");
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))
{
grabableObject = hit.collider.gameObject.GetComponent<GrabableObject>();
if (grabableObject != null)
{
if(grabableObject.isItem == true)
{
PickUpItem();
}
}
else
{
Debug.Log("NoGrabAbleObject");
}
}
}
}
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Used regular threads and it worked well. Thanks for your help!
just make sure you don't touch any unity objects from another thread!
Is there a way to have bindings such that I can have the number pressed in the number row as a value in the CallbackContext of the InputAction?
ClientInput.Primary.Hotbar.performed += ctx => Debug.Log(ctx.ReadValue</* ? */>());
You can look at the input binding that was used to trigger the input action, I suppose
Everyone goes down this rabbit hole for a while before coming to the realization it's just better to make multiple Actions
see InputAction.CallbackContext.control
but yes
each hotbar slot should be its own action
Oh I see haha, I'll let the pioneers lead the way
notably, this will let you bind your hotbars to both the number row and the number pad!
You want to avoid thinking about the input bindings as much as possible
It will also give you proper rebinding support
The input system's job is to trigger actions in response to controller input
I suppose this could just be my perception but it feels like I should be compacting it as much as possible
Each action is a thing you can do in your game.
You don't have a single hotbar action that can be triggered in many ways
You have many hotbar actions that each have a single way to trigger them
if you start peeking at the controller input, you might as well just not use actions at all and directly read UnityEngine.InputSystem.Keyboard.current.digit3Key.isPressed or something
Would you suggest that's a better practice?
No, I think that's a bad idea!
Ohhh mb
since it means you can't do rebinding later, and you also can't support any other input device
Right
you might want to let a controller activate a smaller number of hotbar slots with the face buttons
for example
Suppose I use a an action for each of the 10 hotbar slots, (only 3 are shown, I plan for 10), and then when adding controller support I decide to make the hotbar scrollable, like console minecraft. Would that be challenging to implement?
In that case, you would have separate actions that are only used in the gamepad control scheme
I see, then use those actions to cycle an index or something
probably not what you want to hear, but I've found it best to completely forget the Unity ActionMap stuff and do everything from scratch
and why is that?
How much scratch are we talking?
It's just a damn sight easier and more flexible
Starting from InputControls and building your own InputActions in code
you can manually construct actions, rather than configuring them in an input action asset, yes
i would have to see an example of where this is an improvement
Maybe. Something kind of frustrating is how many different ways the new input system can be implemented. I know that's it to be able to support any and all types of input from mobile all the way to VR but it gets annoying. And the docs are still terrible.
in response to this whoops
The newer versions of the docuentation do a better job of introducing the concepts than the older versions did, for sure
I found it to be overwhelming at first.
wait new docs? I'm still using this site https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/index.html
For example. This is my GamePad and Keyboard setup system. It can be soft configured in Editor or at Runtime
Ermmm link pls?
Have i been looking in the wrong place
All this time
just switch to Manual from Scripting API up top
ohhh
the Manual tab describes how the package works
the Scripting API describes every class/method/etc.
Thank you
I personally use InputActionReference to refer to actions from a single input action asset
along with an input manager singleton that turns action maps on and off based on the current game state
My implementation feels so jank
I use a class as a sort of singleton and just refer to it from any script that needs to bind a function to an action
you're using the generated C# class, correct?
Yeah
Seems reasonable enough.
although putting the cursor locking code in there seems weird
The only reason is that those things usually happen at the same time
I'm making a multiplayer game and the class is only spawned with the player object when they spawn in the server
Hi ! I have an issue with my VR game. I'm working on the Quest 2 in c# , and each time i'm trying to access to a local file (that i've created myself) my app freeze for like 1s and then everything came back to normal. Do you think it's a code error related ? or unity error related ? or Quest 2 error related ?
if you block on the file read, and the file read takes a while (slow storage, maybe), your game will freeze
So, even if i try to do this asynchronously, this will still freeze right ?
asynchronously reading the file would allow the rest of the game to keep running
I'm not sure what the correct way to do this on older versions of unity is, though (i've only used Awaitable in 2023.2.x)
I am trying to get a tangent line on a spline. The tangent should start from the nearest point to my "player". That part works fine.
However when I draw a Gizmo to view the tangent line it is clearly not tangent. I used SplineContainer.EvaluateTangent, which according to the manual should give me a point in World Space.
I have also tried using SplineUtility.EvaluateTangent, then transforming it back into World space butthat gives weird results as well.
I have attached a photo of my gizmo output.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Oh the gizmo is in Red and spline is blue
is that red line perpendicular to the spline?
it's impossible to tell from a single screenshot
supposed to be, but isn't
The tangent is supposed to be along the spline
hence it being tangent
the up vector is perpendicular to the spline
which according to the manual should give me a point in World Space.
A tangent is a direction vector, not a position vector
and yes
you're trying to use a direction vector as a position
the tangent and up vectors are directions
Your problem is you are doing DrawLine which takes two POSITION vectors and you're passing at least one DIRECTION vector into it
but if i use the start point and the tangent vector that should draw the line tangent to the spline right?
oh ok
if you want to use Line it would be DrawLine(point, point + tangent)
been a long time since i messed with vectors in math
you'd better get used to them :p
haha yeah, bringing back memories of college ๐
especially with something as fundamental as positions vs. directions
i'm going to correct that and see how that works, but first time to take the kid to work
put them in an array instead
ohboy
Why have 10 variables that do the same thing, when the only difference is the index
InputAction[] hotbarActions = new IntputAction[] {
Hotbar1,
Hotbar2,
...
}
void AssignHotbarListeners() {
for (int i = 0; i < hotbarActions.Length; i++) {
int index = i;
hotbarActions[i].performed += _ => Hotbar(index);
}
}```
It's the auto generated input system class
Oh great
It's an awkward case.
and yes, this is how I'd deal with it
I similarly use a Dictionary<InputAction,System.Action<InputAction.CallbackContext>> to minimize duplicate code when subscribing and unsubscribing
foreach (var actionRef in callbacks.Keys)
{
actionRef.action.performed += callbacks[actionRef];
}
foreach (var (action, callback) in canceledCallbacks)
{
action.canceled += callback;
}
well, actually, it holds InputActionReference in the first case, but close enough
i should make that consistent
and i should make the iteration consistent

Wait idk if this would work with my system, since I have a separated class for the input system which other classes refer to (my attempt to prevent duplicate instances of the input actions)
that is total overkill
why won't that work?
given that I unsubscribe from the performed and canceled events in OnDisable, this prevents me from having to write near-identical code twice
the only reason to make a Dictionary is if you update the callback context, otherwise 2 arrays is much more efficient
Nvm I would just need to move the AssignHotbarListeners to somewhere else
a marginal gain compared to the convenience of being able to assign the key and value in a single statement
I suppose I could make a list of tuples
not a great fan of developers who think their convenience is more important than the code being developed and run
Feel free to tilt at windmills.
You don't exactly subscribe/unsubscribe player input often
it's a matter of principle
I would have to be doing something truly catastrophic for there to be a difference.
Hundreds of player brains being attached and detached per frame with hundreds of individual actions
I am loading in models at runtime and want to cache them for re-use like a prefab in the editor! But I think there is no way to do this except to import them to scene and make them invisible before Instantiating a copy when required?
I thought code readability/maintainability was a principal on par with performance? At least when collaborating, solo can be different.
These would be equally readable, at least
I might even make the change to a tuple list, since that would allow for multiple functions to respond to a single action being performed
You can make a prefab which has a MeshFilter that is unassigned.
Load/create your Mesh at runtime.
When you want to create a thing you instantiate the prefab then you assign the mesh to the newly instantiated prefab's MeshFilter
not in my book, at least as far as game dev is concerned, app dev is a different can of worms
It is not very high on the priority list, though
I have much bigger gains to make by memoizing most of the objects my AI system is constructing and then dropping on the floor ๐
true - if I can just built the mesh then ok, though ideally prepare materials also and store both ready to input to a new Mesh prefab
Well where do the materials come from
Those can also be part of the prefab, or be applied to the Renderer after spawning
in this case from a prebuild library - yeah I just need to store the data for which materials to add to Renderer later, np
not a great fan of developers who waste a dozen man-hours every time someone has to maintain their code that saves three milliseconds on a function called twice in the entire program's life cycle
missing my point, but maybe you should employ more competent developers to maintain code
We do. That's why they write maintainable code ๐
i can combine any meshes using Mesh.CombineMeshes?
you know, of the 100's of games I've worked on over the years, after publication we have done maintenance on exactly zero of them
Well yeah because once you etched it onto a concrete slab and tied it to the ponies to ship out to customers there's not really much maintenance you can do
A rather odd way to describe any game you would buy in a shop, afaik publishing games to hard media is still very much a thing
Speaking about classes. I've been trying to scout the internet in search for answers, but how can you do things such as using System and using System.Collections at the same time? Wouldn't the global namespace already contain a definition for System? Because when I try doing that I cannot do it
My issue is that I want to have a static class called Generic, but I also want to have one called Generic.Timers for example. How could I do that?
don't conflict namespaces with classes
Whenever you do using <something> you can direct access to any specific members of <something>. Without it, you'd need to fully qualify the type name. For example, a List is actually a System.Collections.List. You could use that instead of any using statements and it'd compile. With just using System, you could use Collections.List to reference the list, but you can only do just List with a using System.Collections
Namespaces are simply part of the name of the class.
Alright then, so for example, if I declare a static class inside of another static class, that would work for what I am looking for, yes?
yes, you could have a static Timers class inside the static Generic class, although I would take issue with your class names
Why so?
because Generic is not very meaningful and both could be easily confused
Looking to optimize this script. It redefines an Image to only have a clickable region along an arc segment of a specified thickness and arc length in degrees.
[SerializeField] float innerRadius;
[SerializeField] float outerRadius;
[SerializeField] float arcLength;
public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
bool baseResult = base.IsRaycastLocationValid(screenPoint, eventCamera);
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, eventCamera, out Vector2 local))
return false;
local /= rectTransform.sizeDelta / 2;
var centerDistance = local.magnitude;
bool inRadius = centerDistance >= innerRadius && centerDistance <= outerRadius;
var angleVector = local.normalized;
var angleValue = Mathf.Acos(Vector2.Dot(angleVector, Vector2.right));
bool inAngle = angleValue <= arcLength * Mathf.Deg2Rad / 2;
return baseResult && inRadius && inAngle;
}
Why are you looking to optimize it though?
Seems like pretty simple math operations already
help me guys
Too many people lately asking for help without asking a question
Also, I told you to post your code correctly
Lazy request
Surely you can make exponential function to fit.
You can use a animation curve then set the gradual increase from sampling the last few points
e^(-x/100) is almost there; you just need to do something to actually reach zero
y = a ^ (x + b) + c, b and c controls the offset in two axis, while a controls how aggressive the curve up is.
I suppose you could do this
The exponent isn't exactly what you're looking for
This lerps between e^(-x/100) and zero over the 0..700 range
No bug report or help forum?
I'm pretty sure I got a Unity bug.
namespace Game.Core
{
[DefaultExecutionOrder(2)] // Run after systems subscribe to state changes.
public class GameControllerSystem : ManagedSystem
{
private void Start()
{
Logger.LogDebug($"GameControllerSystem is starting. Frame: {Time.frameCount}");
GoToMainMenu();
}
The script above always starts before the script below
namespace Game.UI
{
[DefaultExecutionOrder(-1)]
public class MainMenuSystem : ManagedSystem
{
private void Start()
{
Logger.LogDebug($"MainMenuSystem is starting. Frame: {Time.frameCount}");
Whyyyyyy?? These are not in sript order settings, and when they are and the GameControllerSystem is on the bottom it still executes first.
Are they monos?
yes
okay, and what's the actual execution order?
no special logic or anything. They are loaded from addressables, but then spawned normally. Both on frame 1.
Actually never used the attribute, but no clue why it wouldn't appear in the script ordering settings.
Actually there are 3 parameters and you have 3 points, so you can solve the exact values.
if you created these components before you added the attribute, then I would expect them to still have the execution order they were originally assigned
They have no order assigned. I tried it to see if it would fix it, but no. They always ignore any order attributes or settings.
I tried it to see if it would fix it, but no
what is "it"?
Probably has to do with the addressable loading. I'd debug it without loading them first and see if you can manage that.
They execute correctly ONLY if present in the scene when loading..
adding to order settings
so you're synchronounsly loading the addressable assets?
otherwise you wouldn't be able to guarantee which frame the operation actually completes on
I see that you are logging the frame count. I presume they're both printing a 1
assetWithLocation.Asset = Addressables.LoadAssetAsync<T>(location).WaitForCompletion(); Synchronously
I'll try to just spawn directly
you seen this thread?
https://forum.unity.com/threads/undocumented-but-public-defaultexecutionorder-attribute.530618/
There's an undocumented DefaultExecutionOrder attribute for which I don't find any documentation. Is it supposed to work or is it considered internal...
I'd just make myself my own script at that point and initialize them in the ordering I want after getting them from the addressable
So.. I spawned them manually. Very interesting..... Their execution order depends on spawn order. The attributes don't apply. I know the Awake should work like that, but I was certain that Satart() is ordered by attributes and settings....
Start is wonky. Don't depend on it.
The only thing you can depend on with Start is it runs after Awake, period
I'd use Start for general local initialization values. Anything that requires an order of operations should not be included in it.
It's a bug though. Nothing in docs says that it only works for objects that were in the scene on load. https://docs.unity3d.com/Manual/class-MonoManager.html
It's not a bug, the thread says this only works for Awake, which you are not using, and the rest is 'undocumented' still
It does not work for Awake.
It DOES work for Start, but only if objects were in the scene already. And it SHOULD work. It is very useful. It is a BUG.
Uhh I think this is more a quirk opf how Start works
it's not really like other event functions
It's more like all the other event functions like Update, FixedUpdate etc all have an:
if (!startHasRun) Start();``` before them
Start works like Update. Same thing. I'm pretty sure.
no - it's quite special
depending on where in the scene the object was created, it will run before a different event function
I was certain that all starts are executed in order before all updates. I'm pretty sure that it's what docs would say. But if there are more bugs, I'm not gonna be too surprised.. 
private void Start()
{
Invoke(nameof(GoToMainMenu), 0.01f);
}
๐คช
or:
IEnumerator Start() {
yield return null;
GoToMainMenu();
}```
I hate that syntax ๐
or:
async void Start()
{
await Task.Yield();
GoToMainMenu();
}
purely subjectively it's not ugly XD
I could....... Manually read attributes and spawn things in order of the [DefaultExecutionOrder()] Or better custom [SpawnOrder] or [ExecutionOrder].
Magic ๐ช
If Unity fix that bug and [DefaultExecutionOrder] will start working as advertised always, it will break a lot of projects ๐
public fields coming from upper abstract class doesnt show up in the inspector
Can you show the code of those fields?
public abstract class SurvivalObject : MonoBehaviour {
public Transform textPosition;
public string text;
public abstract void Interact();
}
public class ChessBoard : SurvivalObject {
public override void Interact() {
Debug.Log("satranรง tahtasฤฑ");
}
}
```and the upper class
do you perhaps have a custom inspector for the ChessBoard type and just aren't drawing those fields?
Wel, yeah.. idk wha I expected. Pretty straight forward. Should work..
make sure ya project is compiling
this XD
sory for takin your time
probably hadn't compiled then
heyo i've been struggling for a while trying to figure out why my state machine isn't working for a little game i'm making hopefully someone can help me. I have 5 script consisting of State, StateManager, IdleState, ChaseState and AttackState. Watched several tutorials looked up on stack overflow and other places but couldn't figure out a solution. when debuging everyting seems to be fine but the actual enemy never moves and in general skips chase state just goes to attack and sits in one spot. I've had help making the movement component so that shouldn't be a problem.
State.cs --- https://hastebin.com/share/cixuhuvuno.csharp
StateManager.cs --- https://hastebin.com/share/fajefulasa.csharp
IdleState.cs --- https://hastebin.com/share/orawewabud.csharp
ChaseState.cs --- https://hastebin.com/share/xoyujerace.csharp
AttackState.cs --- https://hastebin.com/share/reyolepugo.csharp
i know its a big shout for help but i just dont know what else to do and i don't want to drop this project. Also don't know if this is the channel to ask for help with state machines :))
btw you can post url between <> to skip the embeds
also if you're a beginner IMO this type of statemachine is OVERKILL. You can easily do a simple FSM with an enumerator and a switch
thanks i changed it
thanks! did you check out my other msgs, imo its too abstracted too early make it easier on yourself
Using a coroutine in your states is also kinda suspicious. Your logic should really only be running based on if the state machine calls it to run. And having it return a next state kinda kills any modular code.
Coroutines would make more sense if logic actually needed to run outside like some sort of cooldown
i know should have done more research before starting and now i just want to figure it out this way :))
void GenerateMaterialButtons()
{
for (int i = 0; i < materials.Length; i++)
{
GameObject button = Instantiate(materialButtonPrefab, materialButtonContainer);
int index = i; // Capture the index for the closure
button.GetComponent<Button>().onClick.AddListener(() => SelectMaterial(index));
// Optionally, set a thumbnail or color on the button to represent the material
button.GetComponentInChildren<Image>().color = materials[i].color;
materialButtons.Add(button);
}
}
void SelectMaterial(int index)
{
selectedMaterialIndex = index;
Debug.Log("Selected Material Index: " + selectedMaterialIndex);
}
void ApplyMaterial()
{
if (characterRenderer != null && materials.Length > selectedMaterialIndex)
{
Material[] currentMaterials = characterRenderer.sharedMaterials;
int[] indicesToUpdate = { 0, 1, 3, 4, 7 };
foreach (int i in indicesToUpdate)
{
if (i < currentMaterials.Length)
{
currentMaterials[i] = materials[selectedMaterialIndex];
}
}
characterRenderer.sharedMaterials = currentMaterials;
Debug.Log("Applied Material Index: " + selectedMaterialIndex + " to specified material slots.");
}
}
void SaveMaterial()
{
PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex);
PlayerPrefs.Save();
Debug.Log("Saved Material Index: " + selectedMaterialIndex);
}
public void LoadMaterial()
{
selectedMaterialIndex = PlayerPrefs.GetInt("CharacterMaterialIndex", 0);
ApplyMaterial(); // Apply the loaded material
Debug.Log("Loaded Material Index: " + selectedMaterialIndex);
}
This code applies a new material to my player, this works fine when testing it but when on mobile the material wont change even though the debug logs clearly set and save and load the correct material
For debugging state machines easily I find it nice to have some text object display what the current state is and stuff like how long it's been in the state. Although really going further into a suboptimal solution will likely hurt more than help
I recommend having another script which can decide between what states to enter at least. Or just have a unique way of setting up transitions between states
thats what im trying to figure out
as for debuging i can see which state its it in the inspector
I'm returning to a project I was about half way through, my second real project.
I didn't know about the c# event when I last worked on it, which I should have been using.
Now I can't help but think what other c# keywords, objects, etc.. I should know
I realize that's not really a question lol.
I guess I wonder if there's any sort of "beginner c# unity essentials", "intermediate unity c# essentials", "expert unity c# essentials" anyone's come across?
I guess it's always the way. You could do a extensive c# course and know all the things, and wait ages to start on a project and actually practice.
Or you could learn a decent amount, work on your project, get good practice in, and realise later how many wheels you re-invented lol.
Or I guess I could not be a silly sausage for once, and actually ask for advice throughout my project lol
Anyway, apologies for the ramble, any pointers or advice is appreciated.
If it's any help to you, you are asking the right questions so you are going in the right direction, you'll get there, it just takes time
That is helpful and encouraging, thank you ๐
tbh with time you realize its hard to say what one should learn because we all have different requirements and goals , just my poor 2c ๐
Yea, I think maybe I should get better at alternating, between project work and study, more frequently.
gives me a good idea for a clickbait video title
"20 Absolutely MUST KNOW Unity C# {insert thing} "
Don't you bloody dare, there is enough crap out there already
Tbh besides event I dont think many other keywords will be that important for you. Even event is really just used as a form of restricting what can access your delegate. Similar to using keywords like public private protected
haha that gives me a good idea of what to skim youtube on for gaps in my knowledge
Of course theres the talk of proper design, but as for actually just getting logic working you dont need much
but but..I'm trying to get in on that sweet sweet 20 cents google wants to give me ๐ฆ
at least I didn't make all those "Unity game dev tries Godot for the first time "
And I'm sure nobody deserves it more than you but, clickbait videos,? Don't cheapen yourself
make youtube shorts on unity tutorials like how to do basic things in untiy
manufacture those spam shorts and get a lot of engagement
the more you play around the more you will ask yourself "how do i" and thats how you gain it
tagging #gamedev will get you views
stuff related to unitys UI system helps a lot since there isnt a lot of good guides
let me not even begin to tell you the oversaturation in this space
As much as I hate feeding into the decline in quality, it almost seems par for the course using clickbait thumbnail and title, even by good creators.
make youtube worse
Too true, unfortunately. I think I'll make a series of videos entitled '20 Reasons why you should not take up game dev and actually learn to do something you are capable of instead'
Not the snappiest of titles but I'm working on it
those actually do very well " 10 Reasons why you will hate gamedev"
"10 things I wish I knew before starting gamedev"
Do the clickbait title incredibly over the top and constantly make jokes about how dumb and bad it is so you can get the free clicks but also maintain moral integrity
(But for real though don't hate the player hate the game do clickbait if it works)
๐
I did watch a video titled something about "Why watching Unity tutorials will ruin your life" lol, actually had a good point about people mindlessly following step-by-step tutorials, mechanically following, but not actually learning how to make a game or retaining what they learned.
I saw that one and I thought it was going to be something completely different. Like my tendency to click on an interesting video that shows up on my feed, getting inspired to do a completely new game, wasting two months on it then abandoning it as soon as that happens again
too true ๐ข
It was an overly simplistic opinion though. I got into the Unity UI well using a tutorial course, but watched in stretches taking detailed handwritten notes, actually absorbing the concepts n stuff. Helped that the tutorial actually said what things intrinsically were, instead of just "click this thing here".
I was thinking something along those lines but more basic 'Just because you can play games does not mean you can make them, so don't'
- Use
decimalbecause it's more precise!
Unity bank transaction simulator
Bahaha yes that needs to be said.
I got into it because it checked a lot of boxes, and actually suited my passions, goals, talents, and area's of interests.
- use ChatGPT to do everything!
i'm well on my way to making an epic bacon video
urgh
that hurt to type
I was interested ever since I touched klik and play. Good times.
I used to love making custom maps for puzzle games as a kid. I re-discovered my interest while bumbling around in graduate school.
Also, since the 70's, you must have seen some atrocities lol. Not to sound like clickbait ๐, but I find there's some thing seasoned developers like to tell all us young padawan, or wish they knew when they were younger. What's yours?
A quality video?: I interviewed 10 developers about what got them into game development
Damn good questions, what did I wish I knew when I was younger? Have faith in my vision and don't always try to be on the leading edge. What I would like the youth to learn? That's simple, actually learn how computers work
its weird how we have more technology but people know less about how it actually works
oh Klik and Play was old software for making games on my friends windows 98 pc . I couldn't affort shit
indeed, not just weird but frightening
Have faith in my vision
๐ฉท
Love this
It is a struggle between actually taking good advice, and not letting people who don't have the same vision make you feel it won't work.
I mean sometimes they're right, but I guess you have to try and fail, try and fail, before you do what hasn't already been proven to work.
Well simply put, many jobs simply don't need to know. No one questions on it, no one touches anything related to it. And in a lot of those, we see massive lay offs because they just simply arent needed.
I just mean in general like before jobs come into the limelight
or am i the only one that would break electronics apart just to see how it was all magically working
but I guess earlier products were also more friendly to "tinkering" now everything is some bs factory locked/warranty killer
cars are good example of this
kid is born into an ipad, doesn't care how it works
i just decided today to scrap the particles altogether
But don't you think that anyone who does Computer Systems Development, which is what Game Dev is, should at least know how a computer works?
bringing it back to coding is like using a framework such as Entity Framework to deal with SQL but then if something breaks on the database now you have no clue how SQL works because you meerly interacted through abstraction and cannot fix the raw SQL tables n shit
I recently filled the gaps in my knowledge with a course that went though the whole OSI.
It makes me feel much more complete in some way, to be able to look at tech and know from start-to-finish how the information flows, there's no magic black-box at any step in my brain.
ideally
Thatd be ideal, of course itd be better if people knew what they were doing. But reality isnt ideal, people lie on resumes and you simply cannot test enough before hiring someone.
If we are talking about someone just doing game dev as a hobby, most arent patient enough to do the basics even. And their products dont affect me so doesnt really matter
I loved pulling apart electronics as a kid! However.... putting them back together I was less good at ๐
hahah yeah, the amount of "shit now comes the hard part, let me just leave this like this no one will notice this wire now sticks out from the sides "
I started volunteering at place that takes ex-corporate laptops, refurbishes, and gives them away.
They have these things which are great
ohh yeah these days, its much easier lol now I just recordmyself from fpv taking it apart and just playback backwards
also we're getting a bit offtopic from unity coding ๐
That's a great idea, often i've taken pics for things like where to thread a laptop cable
oh lol yes
How can I change / update at material on my player on button click, ATM it only does it when i restart the game
void SelectMaterial(int index)
{
selectedMaterialIndex = index;
Debug.Log("Selected Material Index: " + selectedMaterialIndex);
}
void ApplyMaterial()
{
if (characterRenderer != null && materials.Length > selectedMaterialIndex)
{
Material[] currentMaterials = characterRenderer.sharedMaterials;
int[] indicesToUpdate = { 0, 1, 3, 4, 7 };
foreach (int i in indicesToUpdate)
{
if (i < currentMaterials.Length)
{
currentMaterials[i] = materials[selectedMaterialIndex];
}
}
characterRenderer.sharedMaterials = currentMaterials;
PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex); // Update PlayerPrefs immediately
PlayerPrefs.Save(); // Save PlayerPrefs immediately
Debug.Log("Applied Material Index: " + selectedMaterialIndex + " to specified material slots.");
}
else
{
Debug.LogWarning("CharacterRenderer is null or materials array is empty or selectedMaterialIndex is out of range.");
}
}
void SaveMaterial()
{
PlayerPrefs.SetInt("CharacterMaterialIndex", selectedMaterialIndex);
PlayerPrefs.Save(); // Save PlayerPrefs immediately
Debug.Log("Saved Material Index: " + selectedMaterialIndex);
}
public void LoadMaterial()
{
selectedMaterialIndex = PlayerPrefs.GetInt("CharacterMaterialIndex", 0);
ApplyMaterial(); // Apply the loaded material immediately
Debug.Log("Loaded Material Index: " + selectedMaterialIndex);
}
what does clicking the button actually do?
Is the log printing ?
is it possible for Object A to detect if Object B is colliding without attaching a script to Object B?
the only objects that will be sent a message upon collision are the two objects involved in the collision (or their rigidbody if they are a child of a rigidbody)
General question โ does anybody here feel like they deeply understand quaternions beyond the Unity functions that transform them?
I am unsure how deeply of an understanding of quaternions can help when coding them
they just do
I see no reason to understand quaternion math
even less than understanding the math behind transform matrices
does anyone understand quaternions?
I used to at one point but the knowledge is simply not that useful
I used to have a basic understand, as I needed them for creating a calibration procedure for a magnetic tracking system
I just feel a bit uneasy putting Quaternion.Euler functions in my code, seeing a positive result, and depending on that to remain consistent without a good understanding of how reliable it actually is under the hood
I can operate on looks good is good
what if Vector3.Distance secretly didn't work on Tuesdays?
If I were a math wizard and understood the fourth dimension of rotation through and through
If you are using the methods correctly, you can be confident in what you're doing
I don't use Quaternion.Euler much; I mostly use Quaternion.AngleAxis
I find it a bit easier to reason about
as long as you're confident in what values you put in, theres really no reason to have doubts. The only operation you really do with quaternion is "adding" your rotation. To answer your question above on if people deeply understand them, id be surprised if more than 10 people here do. Like I know what Quaternion * Quaternion is used for but the actual math behind it is more complicated. Unity simplifies it for you, the actual math is like Q x P x Q^-1.
Okay, that makes sense. I heard that very few people understood quaternions and I was uncertain if that was an exaggeration or a shortcoming.
There was one time a few months ago I made a mistake in my camera rotations which was exclusively caused by some Quaternion issue and I was wondering if it was worth learning more in-depth. I suppose not
The specific issue was a camera max-pitch min-pitch limit being exceeded when the camera's Z-rotation flipped from -359 to 0, iirc
that's not really a quaternion issue
in that case you're just getting surprised by how euler angles wrap around at 360
Its definitly true if we take "understanding it" as you know the math and can do it by hand. I tried looking into the math once, which is why i know that Q x P x Q^-1 thing, then got reminded of 4th year linear algebra and immediately gave up. ๐ โโ๏ธ none of that for me
And if you need euler angles, its best usually to keep track of your own euler angles if possible then do logic. Sometimes it isnt possible like if you have some rigidbody which is being knocked around because those values will drastically change while the actual object didnt move much.
I think they were properly limited, but if I looked up or down and then rotated left or right, the euler angle would not respect its initial position, so -90 and +90 should have been hard limits, but looking as low as possible and rotating left or right would change these limits. The cap I had initially set was supposed to stop any possibility of this
Okay! I deleted all the cached files and made unity rebuild everything from scratch, the errors are a little more comprehensible this time.
It seems like everything is stemming from (this)[https://hastebin.com/share/ilehiraxik.vbnet] one
The creation of Packages.Rider.Editor.RiderScriptEditor is failing for some reason, inside CsprojModifier.Editor.Features.InsertAdditionalImportFeature.OnGeneratedCSProject
Anyone knows how to fix bullets phasing through walls? sometimes it doesn't sometimes it does
I tried using Continuous collision detection on the bullets but they still phase through the wall. :/
how are you moving the bullets
show move code
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i instantiate the bullet then change the velocity
is the speed like really high
well most bullets are faked
if you want precision
the video didn't really answer how much speed are you putting in ? Continuous should be able to help, if not you can try just doing a rb.SweepTest
160
sweeptest? ill go read on that! thanks :3
hmm maybe try less speed but instead of setting velocity directly do AddForce, Force.Mode.Impulse maybe
I would just raycast really, you dont need a rigidbody if you're faking it anyways
I did hear sometimes setting velocity directly can cause odd behavior
rigidbody are easy to deal with when it comes to bullet trails, bullet drop etc.. but painful in these situations
there isnt a real difference, especially since they're just doing this once
the literal only difference i can think of, is that this would be set immediately and not during the physics step
hmm yea something to test for sure, I'll check it out
that was something i noticed before, with addForce and trying to immediately limit a rigidbodies velocity. the velocity is applied after so limiting it right away does nothing
i might just go for raycasting to hit enemies with bullets but still not sure how to make the bullets stop going through walls, even if its fake
impulse still takes into account deceleration while velocity doesn't
raycasts automatically hit colliders, aka walls
no way they gon miss lol
if you need fancy shite like bullet trails you can easily just lerp from startpos to hitpoint / infinte ray
ayo?
Anyone might be available for reading and criticising my interaction code? I want to improve/optimize it so bad but i have no clue what or how to do so.. 
You can try posting the !code and maybe ask specific concerns you have
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
imo , ask yourself few things if its working.
1 are you going to extend this script
2 are you able to read it clear, and know what's going on at a glance
If you answer yes then you're good to go
Hey guys, quick question for those of you who use Visual Studio, how do I not proceed with a suggestion it offers me? When it thinks it knows how to correct what I'm doing I don't know how to tell it to not proceed with the correction aside from ctrl+z after the fact, a little annoying when it's so obviously off the mark.
Try Esc. Or just don't press the auto complete key.
switch intellisense mode to Tab only
(don't forget to restart vs ofc) ๐
godsend, thanks a bunch
The annoying part was that it didn't require anything, if I just keep typing it autocorrected by itself, I'm all in for "tab to apply" suggestions, not ones that change my code without my input. Esc worked tho, thanks
Oh, I didn't know it was applying the changes automatically by default.
I want to replicate this curve in my AnimationCurve, is there a way, or do i just need to eyeball it
You'll need to eyeball it. Or just make the exact function in code.
oh i dnt know there were functions to edit animation curves
public class Backpack : MonoBehaviour {
[SerializeField] BoxCollider check;
Dictionary<GrabInteractable, Action> previous = new();
void Update() {
List<GrabInteractable> overlap = Physics.OverlapBox(check.transform.TransformPoint(check.center), Vector3.Scale(check.transform.lossyScale, check.size) / 2, check.transform.rotation)
.Select(x => x.GetComponent<GrabInteractable>())
.Where(x => x != null)
.ToList();
foreach (GrabInteractable grab in previous.Keys.ToList()) { // Are you still there?
if (!overlap.Contains(grab)) {
grab.onDropped -= previous[grab];
previous.Remove(grab);
print($"Removed {grab.name} from previous");
}
}
foreach (GrabInteractable grab in overlap) {
if (!previous.ContainsKey(grab)) { // Are you new?
Action droppedAction = () => PutInBackpack(grab);
grab.onDropped += droppedAction;
previous.Add(grab, droppedAction);
}
}
}
void PutInBackpack(GrabInteractable item) {
item.transform.SetParent(transform);
item.rb.isKinematic = true;
}
}```
Look at this piece of shit
I hate how this works. From the linq to the backwards iteration
What's a better way of doing this?
to paraphrase
- Overlap all grab interactables in the backpack area
- Compare the current overlap to the previous one, remove anything that is no longer there and unsubscribe from the OnDropped method (in case you decided to change your mind about putting an item in the backpack)
- For every grabbable, subscribe to make sure that when you drop it in, the item is put into the backpack
that's going to spew a lot of garbage every frame
Yeah
overlapbox();//use an existing buffer0 (List<Collider>)
buffer1.clear();//List<GrabInteractable> again an exisiting buffer1
for(collider in buffer0)//for or foreach loop
try get component then add it to buffer1
now you have two lists (sets) ofprevious stored GrabInteractable s and currently overlapping GrabInteractable s
since the number of GrabInteractable s is small, so i think you dont need to use dictionary or hashset, juset iterate and find
if the number is large, then ofc use a hashset or dictionary
not large
The reason I was using a dicitonary is because the event is subscribed with an anonymous method, I need to somehow keep track of that action that I subscribed to, in order to remove it later
Your psuedocode is a little bit too psuedo for me, sorry. I'm confused on some parts. Can you elaborate?
do you even need the anonymous method there, it looks like you can just directly subscribe/unsubscribe
I need to pass in grab, the item to be put into the bp. The event is a simple Action so it can't take parameters.
you can make a pair of <GrabInteractable ,Action>
same as what dictionary does
Hello all. I'm wondering if anyone may know of a way to read specific values of variables of a property drawer? I am trying to use a scriptable object with a property drawer to contain a specific set of audio files, and then use a gameobject to reference that (or any given) scriptable object and then call a method which then returns my audio clip. An example of what I'm trying to do (in a completely made up section of code):
ScriptableObject SO;
AudioClip audioclip = SO.ReadAudio(n)
~~~~~~~~~~~~~~~ How this would function inside
ScriptableObject.ReadAudio(int n) => return ScriptableObject.PropertyDrawer.Sections(n).GetValue("AudioClip")
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
```a custom struct or use tuple a use named method so you dont need an additional field to store your anonymous method
why bother with a property drawer at all? This would be editor only and seems like the wrong solution based on your description
what the fuuuuuck....
Yeah I can't use a named method. I need to pass in the parameter to PutInBackpack
I don't understand what the custom struct would do here
im using it to contain different sections of audio which will all flow into each other. A way to handle dynamic music. I know it seems impractical. Its to contain each section of a song, but then have that section loop until a specific event is triggered, but have the same code run for all of the songs. This would allow me to only need to focus on what song (scriptable object) is being input into my music handler, and it would control which section is played and looped and such. (I'm sorry. I'm not doing a good job at explaining this). If anyone has a better idea for a way to handle my issue, I'm all ears lol.
//in your GrabInteractable.cs
public Action<GrabInteractable> OnDropped(GrabInteractable x)
when invoked:
OnDropped(this)
```idk if this works in your case
then you can subscribe it by just
grab.onDropped+=PutInBackpack
The idea is to add this feature without changing anything in the underlying VR system, cs public class GrabInteractable : MonoBehaviour, IInteractable { public event Action onPicked; public event Action onHold; public event Action onDropped;
They are just generic actions
Grab interactables shouldn't need to know about the existance of backpacks
Not sure if this is the right channel, but I am having some issue with Camera Stacking
What I want:
- The whole game to be rendered with a post processing effect applied to it
- Some special sprites that get rendered without post processing (World space UI, but I am not using the UI system. I am just using sprites)
It seemed trivial to do so by using camera stacking, but what happens is that the second camera (world space UI) removes the post processing effect from the base layer
Any idea if this is a bug? Or if I am missing some additional setting somewhere?
The expected result should be a yellow-green square with a white circle over the top of it
Then use a tuple to store the action with the grab interactable
Unity 2022.3.5f1 btw
I'm guessing your other camera just draws on top. Each camera should exclude things you don't want to be redrawn
post processing is a camera space effect, other camera can't affect post processing of the first one
When I show the preview of the top layer it looks like it is correct
So they are separated correctly in what they are rendering
make sure post processing layers setup correctly
I will recheck those
Ok so my PP is on Default Layer
My main camera is set to volume mask default and PP turned on
My overlay camera is set to volume mask world ui and PP turned off
I dont have any PP for the world UI
It seems like the correct setup to me?
If I add a world ui PP volume then it renders both layers with that PP resulting in both layers being blue
One should be yellow and the other blue
I mean it's kind of code related, no?
Haven't touched camera stacking in a while. I'm guessing it has to do with Volume masks overlapping incorrectly. You should move the post to #๐ฅโpost-processing with all the illustration and mention what render pipeline you are using as well. Cause camera stacking works differently, I think, in URP for example.
Oh yeah I did not realise there was a channel for this
Thank you
Turns out it has to an instance of an object and not a prefab for it to work
I was able to fix my problem
By setting Stop NaNs on the base camera to true, it magically works lol
In my case I don't intend to have a separate PP effect on the UI layer so its completely acceptable
For people who do want that this won't work for them as any PP on the top layer will also apply to the lower layer too
I've been working on Interaction Controller and I found myself confused. Is this a good approach to handling interactions? There is base abstract Interactable class that, currently has Activatable and Collectable. I am handling this through **raycast **like this. Is this the best approach I could use in my scenario?
Every other way that I tried made confusion. So if someone can help me with forming better structure, I would be really thankful.
bro what. this honestly doesnt make sense, even AI is saying something is wrong
if im using else
does that not complete it???
This isnt a unity question, as already said in #๐ปโcode-beginner there is a c# discord you should post there.
Your "1" and "2" branches don't return anything.
This is more of a #๐ปโcode-beginner question though.
btw, have you even tried googling this, or are you using Discord in place of a search engine???
it is, but they respond with "Console.WriteLine is not a c# line its a java line ๐ค "
so sorry again
in C# to return a value you must use return <something>. Contrary to some other programming languages (idk, python?), the return must be explicit.
Best approach is kinda debatable here. If this works for your use case then carry on. I'm not a major fan of needing to check for every single derived type especially if this grows larger. It kinda takes away from the whole point of interfaces although I see why you use it here.
It could be nicer if the classes just implement methods which happen on interaction, which is really what this interface implies. Then suddenly you wouldnt need to cast for each derived class, and this code wouldnt need to change everytime you have a new interaction.
ok it worked @chilly surge the bob tabor c# beginners guide has the code exactly like mine, must be a c# update or something idfk
So? This isnt unity related. Similarly you dont see people posting python or java saying "its code"
i want to be mean to you, but i need this discord for help
!cs
so im just gonna say ok and be quiet
Bot isnt working rn and we cant link discord cause its blocked
oh i see
I know, but then there is another problem. I need to pass one argument **Transform ** of hand position to collectable items. So Collectable item's need their own method. I don't quite know how I would structure that.
Yes but this is unity specific. There are pretty major differences, which led one person to tell you Console.WriteLine isnt c# because we really dont use it here along with other stuff. This is a link to a bot message for the c# discord
#๐ปโcode-beginner message
ok bawsi ur right im wrong
Yea that really is one of the reasons why I say if this fully suits your use case then just carry on. The only immediate solution I could think of is creating a class which is always passed around to interactable methods, then give it like a field for Transform and whatever is needed in the future.
Did that, but because I am working with Mirror I can't directly assign hand to item.
Maybe someone else has a better method for this, im about to sleep though so brain not working
I'm not entirely sure what that means also, I dont use mirror
Is it good to put ScriptableObjects inside Resources folder?
IInteractable could expose an Interact method which takes in a transform. If the item doesn't care about the transform it's fine to just ignore it.
I have a prefab player, and I can't just extract hand from it, and put it as a reference in the inspector. It's an error. I had a really good structure without applying mutliplayer.
Yeah, but that's not really clean is it? There is a lot of overriding being done.
Why not?
I might be missing some context, why would IInteractable having a method requires overriding?
In your case yea I'd even opt for what Burrito is saying. Interfaces usually will result in some empty methods/unused parameters which people say isnt clean but ๐คทโโ๏ธ who cares
Did that, seems fine. Thanks!
Thanks.
when I set this field (pic 1) by other script and it's not null - throws me this error Fields with [SerializeReference] cannot serialize objects that derive from Unity.Object
but it still serializes it in inspector (pic 2) and working fine, only throwing constantly this error in console on field set and that's all
am I doing something wrong with it? also, serialization result looks strange with this drop down for a type, lol
Close and reopen Unity just for fun.
nope, still remains after reopening
Strange, from what I nkow it should not work.
Anyway, you should not use this pattern and ignore Unity warning because you are going to be bitten in the ass at one point or another.
Probably something else is happening which "make it works".
SerializeReference are used for embeded C# object, not scene reference.
hm, got it, thanks!
are you using Odin Inspector by any chance
i know it provides an inspector UI for [SerializeReference]
although it still should not appear in this case, since the field isn't serialized
maybe it'd appear if your inspector was in Debug mode
but I'd expect the inspector to look a bit different in that case
I'm using TriInspector (open source Odin-like with less stuff), so maybe it's because of it, dunno
Ah, that might be it
Although I'm still surprised it's serialized at all.
Unity does secretly serialize private fields that aren't explicitly marked with System.NonSerialized
so that they can be shown in debug mode
Perhaps TriInspector is picking up on that and displaying it, even though it shouldn't be included in the inspector
You can test this by adding [System.NonSerialized] to the field
Hey, i wanted to ask if anyone could help me with some issues regarding TextMeshPro on android
for some reason I canยดt enter any . or , when im typing something into the field (see the video above)
i set the content type to "decimal number", but it doesnยดt register when im typing them on android (it works fine in the unity play mode on my pc)
this bit me once: unity wound up putting some garbage values into private InputAction fields
I've removed TriInspector from a project and now it not serializing, yeah (I was using it just for easy read only field in inspector, because I'm lazy to write my own property drawer, lol)
And I think it serialized it because TriInspector uses NewtonsoftJSON, maybe this because of it and it's internal shenanigans
Also, strange drop down removed too, hehe
yeah, I mean its serializing through it
Hey, I've a problem with my PlayerController if anyone know why ?The player walk in front of him alone and the movement controller doesn't work correctly.. Thanks you
public class PlayerController : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
ping me please
I feel like it's so complicated to manage PlayerController and MouseController script ..
Has anyone got SpriteShapeSegment.spriteIndex setter to actually do anything in a SpriteShapeGeometryModifier? It seems that modifiying the sprite index (inside a job) does not change the sprite that is actually rendered to the screen.
relevant code is
IJob:
public void Execute()
{
for (int i = 0; i < segmentLengths.Length; i++)
{
int chosenSpriteIdx = FindLeastStretchedSpriteIndex(i);
for (int j = 0; j < submeshesPerSegment; j++)
{
SpriteShapeSegment submesh = submeshes[i*submeshesPerSegment + j];
submesh.spriteIndex = chosenSpriteIdx;
submeshes[i*submeshesPerSegment + j] = submesh;
Debug.Log($"submesh {i*submeshesPerSegment + j} sprite index set to {chosenSpriteIdx}");
}
}
}
MakeModifierJob:
StretchMinimisingJob job = new()
{
submeshes = submeshes,
segmentLengths = segmentLengths,
spriteLengths = spriteLengths,
submeshesPerSegment = submeshesPerSplineSegment
};
JobHandle jobHandle = job.Schedule(generator);
//dispose of NativeArrays after job is complete
JobHandle disposeHandle = JobHandle.CombineDependencies(jobHandle, segmentLengths.Dispose(jobHandle));
disposeHandle = JobHandle.CombineDependencies(disposeHandle, spriteLengths.Dispose(jobHandle));
return disposeHandle;
What this is supposed to do is make each segment of the spline use the sprite variant that results in the least distortion. But even if I force each SpriteShapeSegment to use spriteIndex 0, nothing happens and it keeps using whichever one was manually defined in the editor.
Actually I realise now that I can modify the spline's sprite variant directly without using geometry modifiers and jobs, so now the question becomes how do I detect when the spline has been changed? I don't see any callbacks, will I have to do it through OnValidate in a component that inherits from SpriteShapeController?
hi
jumpingForce = Vector3.SmoothDamp(jumpingForce, Vector3.zero, ref jumpingForceVelocity, JumpingFalloff);
the code above runs on update.
if I change the value of jumpingForceVelocity on the inspector to something like 1 or 0.1
it keeps going down close to zero then snapes to something like -7 then dumps down to zero then snaps again and again
what is going on ?
jumpingForceVelocity gets modified by SmoothDamp, the variable ref'd there is only meant to keep track of the rate of change between calls so it shouldn't be exposed to the inspector
To configure how quickly SmoothDamp approaches the target value, you adjust the fourth argument -- the smoothTime
SmoothDamp(value to be moved towards target, target value, ref current rate of change, estimated damping duration)
I'm trying to make an Item system with modular Effects on each item (like "add health", "remove speed", etc.)
I'm storing Item stats as JSON, but can't figure out how to add Effect definition to this stuff properly
My first thought was to make just a special key-value pair inside JSON as a list named "effects" with strings for type names I've made as an Effect class and just create them as plain C# objects at initialization for each item with Activator and cache it in ScriptableObject "database", but I barely think this is the right way of doing it, lol.
And other way I'm thinking of is: ditch JSON, make ScriptableObject for each item and then create each item effect as ScriptableObject too that can be referenced in each item. But, I need to pass a player/npc in it and cast to proper interface each time I use an item, because I can't cache my casted user object in EffectSO or ItemSO, because it's scene objects and will be shared between items.
So, how to do it more properly? Or can someone point me to right direction for implementing this system?
ok I hide it
there is another issue tho
move.y += jumpingForce.y;
controller.Move(move * speed * Time.deltaTime);
the above code makes player stops movement in all direction and only jumps in place.
like if he is moving forward then hit jump , he stops and only jumps upward, strictly upward not adding the jumping force to the current movement
Using SOs is much easier than trying to do it with JSON so that's a good idea. Your code structure is flawed if your item/effect templates need reference to scene objects, the templates should not know about the scene and instead you'd prob want something like an item instance monobehaviour which gets any necessary references during runtime. Also the casting to interface is a red flag in this situation, using an item should go something like entity.heldItem.Use(entity, target)
Yeah, I'm leaning towards SO for this, but still there are problem with passing users and their type:
Item effects will need user and target reference that are passed through some method (I'm obviously not caching scene objects inside SOs, my wording in that post was bad, sorry), so there are will be needed a cast from an object type argument to some common interface of an item effect that supports it, so anyone can use an item with effect if they implement an interface
Main problem is I can't do it without casting, so my item effects inside item is share base class EffectBase or smth like this, so they can be stored inside an Item SO. I want my items and item effects to be generic, but I dunno how to do it for caching item effects inside item without casting it or target user when use it, lol.
can i get several terrains, convert them to meshes with heightmaps and textures, combine them to a single mesh and use as entire world's LOD?
well, i can definitely take heightMap
alphamap textures for the texture then refer to their width and heigth for splatmapping
terrain blends textures together
and it's called a splatmap
it's all in the terrain asset so probably
I do populate my terrain using the texture masking
at runtime that is
When you paint on terrain, you're painting a single channel of a "splatmap"
Unity Terrain has two splatmaps with R/G/B/A channels, so you get to use 8 different terrain layers
Each channel tells you how much weight a specific terrain layer gets
(i think it's normalized)
so a red channel value of 1 means that the first terrain layer is displayed
green and blue values of 0.5 mean layers 2 and 3 are mixed 50-50
I'm not sure if I fully understand what you mean but if I do, you can have it with generics:
public abstract class ItemEffect<T1, T2> : ScriptableObject where T1 : IItemUser where T2 : IItemTarget {
public bool IsUserValid(IItemUser user) {
return user instanceof T1;
}
public bool IsTargetValid(IItemTarget target) {
return target instanceof T2;
}
public T2 GetTarget(GameObject go) {
return go.GetComponentInParent<T2>(); //may be null
}
public abstract void ApplyEffect(T1 user, T2 target);
}
public interface IHealable : IItemTarget {}
public class Player : MonoBehaviour, IItemUser, IHealable {} //can use items, be targetted, and be healed
public class Enemy : MonoBehaviour, IItemUser, IHealable {} //same as player
public class NPC : MonoBehaviour, IItemTarget {} //cannot use items, cannot be healed
public class AreaOfEffect : MonoBehaviour, IItemUser {} //cannot be targeted, but can use items
//subclass example, you need this to make SOs with defined generic
public class HealingEffect : ItemEffect<IItemUser, IHealable> {...}
//naming: effect(user)(target) where X = any, P = player, E = enemy
ItemEffect<IItemUser, IItemTarget> effectXX = new(...);
ItemEffect<Player, IItemTarget> effectPX = new(...);
ItemEffect<Enemy, IItemTarget> effectEX = new(...);
ItemEffect<IItemUser, Player> effectXP = new(...);
ItemEffect<IItemUser, Enemy> effectXE = new(...);
ItemEffect<Player, Player> effectPP = new(...);
ItemEffect<Enemy, Enemy> effectEE = new(...);
HealingEffect effectHealing = new(...);
Depending on the amount of textures, you need to iterate over the alpha map with each specific texture and grab the weights.
https://docs.unity3d.com/ScriptReference/TerrainData.GetAlphamapTexture.html
Ah, right this is the single channel refer to GetAlphaMaps then if you want the independent layer channels. Basically, you can use a shader with this and be done with it, but if you want to bake the texture data then you want to use GetAlphaMaps.
yeah -- that's a single-channel texture
I wonder if the splatmaps are stored as eight separate one-channel textures internally
I just know that they're presented to the shader as two four-channel textures
oh there's this one too
https://docs.unity3d.com/ScriptReference/TerrainData.GetAlphamaps.html
float[,,] A 3D array of floats, where the 3rd dimension represents the mixing weight of each splatmap at each x,y coordinate.
So I think z is each layer here (kinda like how the texture arrays work)
Holy, thanks!
I was thinking about something like this with interfaces and generics, so maybe it's the right way
yes, and you can prob come up with a better implementation using this idea than I gave cause I conflated item with effect whereas in your game there may be entities that can apply effects to you but can't use items for example (the effect may come from a different source).
Hey, I'm trying to make my game playable on pc (keyboard) and mobile, so I set UI buttons with an On-Screen Button script. Only problem is I don't know which control path I'm supposed to use (and the keyboard and dpad options don't end up working).
ItemEffect<TUser, TTarget>
so by getAlphamaps i get an array of floats
Then i somehow build up a texture
it gives you the weight of the position
and then i apply it to mesh i generated out of terrains heightmap?
so you apply the texture now of those coordinates with the weighted value blended with the other textures
i just want to paint a non-textured mesh with terrain's colors
maybe i don't get smth, but why do i need to blend my map with other textures, if generated mesh has none
take a brush and use two textures in the same spot on the terrain with 50% strength
oh you mean it's a step before getting the resulted map
what is the difference between this and just using the terrain?
i want to have a very large mesh made out of all terrains i have in the game
but very low-detail
ahh I see
to use it a lod for distant parts of the world
so i can get all terains, set pixel error to max amount, convert the thing to mesh, do this for all terrains and then use Mesh.combine
and then i also need to apply textures of those terrains to mesh parts
so in game it looks like there are terrains, but actially it's like 5k faces(or 50k idk never measured) curved plane
I wonder why there's a limitation of layers with the terrain
is that really a thing i should think about
hdrp doesnt seem to have that limitation though
i'm on urp by now
hdrp is too hard
and also my grass shader doesn't work with it XD
oh huh open gl also has a limitation of 4-8 textures
I believe the point of an on-screen button is to emulate input from a controller
Hey, I am trying to draw a field that cannot be drawn in the data structure in inspector.
Do I need to draw all the remaining fields manually just to do this?
I just want them to stay the same.
At the same time, since the serialized data is an object, it uses ISerializationCallbackReceiver, when I create a field with the custom property drawer, does this field I created have an onChange callback or a similar structure because I need to manually control the change.
What kind of control did you try assigning?
More details? Share code? Explain the goal here? Note that serialization is more than just showing in the inspector. It also controls whether the data is saved in your assets or not.
[Serializable]
public class GPNodeData
{
public GPNodeType NodeType;
public string GUID;
public string NodeTitle;
public bool Expanded;
public GPSerializableVector2 Position;
public string Data;
public GPConnectionData ConnectionData;
}
public class GPSelectorNodeData : GPNodeData, ISerializationCallbackReceiver
{
public object SelectionValue;
[SerializeField,HideInInspector] private string _valSerialized;
}
as i'm thinking
does mesh.combine take texture or the mesh only
public void OnAfterDeserialize()
{
SelectionValue = DeserializeValue(_valSerialized);
}
public void OnBeforeSerialize()
{
_valSerialized = SerializeValue(SelectionValue);
}
public static string SerializeValue(object value)
{
if (value == null)
{
return "n";
}
var type = value.GetType();
if (type == typeof(int))
return "i" + value;
if (type == typeof(float))
return "f" + value;
if (type == typeof(Color))
{
Color32 c = (Color)value;
uint v = (uint)c.r + ((uint)c.g << 8) + ((uint)c.b << 16) + ((uint)c.a << 24);
return "c" + v;
}
if (type == typeof(GPSerializableVector2))
{
GPSerializableVector2 v = (GPSerializableVector2)value;
return "w" + v.x + "|" + v.y;
}
if (type == typeof(Vector3))
{
Vector3 v = (Vector3)value;
return "v" + v.x + "|" + v.y + "|" + v.z;
}
if (type == typeof(bool))
return "b" + value;
if (type == typeof(string))
return "s" + value;
throw new ArgumentException("Unsupported value type: " + type);
}
it combines the vertex data, and it must have the same material between them all
two ways you do it, bake the textures or do it by shader
@leaden ice I am just trying to make that SelectionValue to editable in inspector also trying to make sure there is no error after editing due to serialize,deserialize etc.
What errors are you getting?
What's going wrong?
isn't that a on-screen stick?
controllers have buttons too :p
left-right (keyboard)
show me exactly what you picked
okay, that looks fine
that should create a virtual keyboard
You can see if it's actually being created by looking at the input debugger
I would expect it to show up in this list
@leaden ice
Reasons why I cannot draw a propert field based on _valSerialized,
I can't get the current value in _valSerialized, I can't find a target like in customInspector.
The only thing I found is serializedObject and I can't cast it to GPSelectorNode data.
When I draw it and a wrong value is written into it, the things I did in OnSerialization with a method like onChange cannot be applied and the data there is corrupted and serialization errors come.
At the same time, I can't open an extra field just for this field, I need to make all the fields of GPNodeData and when I add something, it doesn't look like the old first version.
looks pretty much the same (unsupported is just the extra buttons on my mouse)
and other usbs
first way is the splatmap way ig
Convert unity terrain to mesh, Programmer Sought, the best programmer technical posts sharing site.
i found this thing, but sadly no screenshots xD
Could someone tell me their opinion on using switch on Vectors this way? Does if look more appropriate to you?
private void SetTorsoEdge(int index, Vector2Int direction) =>
SetTorsoTile(index, (direction.x, direction.y) switch
{
(0, 1) => playerBody.torso.tileEdgeUp,
(0, -1) => playerBody.torso.tileEdgeDown,
(1, 0) => playerBody.torso.tileEdgeRight,
(-1, 0) => playerBody.torso.tileEdgeLeft,
_ => throw new()
});
It's fine - you could also use Vector2Int.up etc to make it more clear semantically
It's not constant though?
That's why I'm asking whether converting it into a tuple looks fine
you're using pattern matching so it shouldn't matter, no?
Admittedly I don't use pattern matching switches that much so I may be mistaken
Using a non-constant value in a switch throws me an error. Surely, I would like to do it this way
private void SetTorsoEdge(int index, Vector2Int direction) =>
SetTorsoTile(index, direction switch
{
Vector2Int.up => playerBody.torso.tileEdgeUp,
Vector2Int.down => playerBody.torso.tileEdgeDown,
Vector2Int.right => playerBody.torso.tileEdgeRight,
Vector2Int.left => playerBody.torso.tileEdgeLeft,
_ => throw new()
});
you got two params there
But this is a problem in switches
Yeah pattern matching unfortunately require compile time constants.
or maybe im reading this wrong.
Ok I guess I was mistaken about pattern matching switches
Could do an enum, no?
Yeah, but the Vector would have to be converted every time
A Dictionary<Enum, Vector2Int>? Shouldn't the methods to convert it be slightly more comfortable?
private static Vector2Int GetValue(this MyEnum myEnum) => myEnum switch
{
// ...
};
It's up to preference. Switch is probably more performant if you care for it considering the amount of entries.
I've a habit of mapping everything though.
Looks like a perfect use case for a look up table!
An array with the precomputed values and using the enum as an index.
Question,
Is it possible to call a script & gameobject in a clone of a prefab?
When my players spawn, they have a player prfab clone with the playerManager script attached,
Altho, i want to call a game object & script out of my scene, but if i use
public GameObject ObjectName
I cant assign it to the prefab, is there a way to do this ?
i also tried this:
public void Awake(){
GameObject.Find("ChatManager");
chatManager = chatManagerGameObject.GetComponent<PhotonChatManager>();
}
Seems not the be the way
Find() returns a value, you're not storing it in a variable. chatManagerObject = GameObject.Find("ChatManager") would perhaps do what you want.
An alternative would be to let the script that instantiates the prefab (which is in the scene, so it can have the reference) pass the reference to the PhotonChatManager directly
Also avoid posting the same question in multiple channels at the same time.
Jep! That did the trick,
private PhotonChatManager chatManager;
private GameObject chatManagerGameObject;
public void Awake(){
chatManagerGameObject = GameObject.Find("ChatManager");
chatManager = chatManagerGameObject.GetComponent<PhotonChatManager>();
}
[PunRPC]
public void SetNickname(string _name){
nickname = _name;
chatManager.nickname1Text.text = nickname;
chatManager.nickname1GameObject.SetActive(true);
}
Sorry about that! ๐
never worked with calling prefabs / scripts in prefabs, was just a little hyped haha!
https://cdn.discordapp.com/attachments/497874004401586176/1251217932785291375/image.png?ex=666dc701&is=666c7581&hm=e8a4784b5f412b3c2a05bce162ccadf4e878b6c58afd05bacce777e10563165a&
https://cdn.discordapp.com/attachments/497874004401586176/1251217933095538688/image.png?ex=666dc701&is=666c7581&hm=6e6497b47f94ff9ddb43b8a52ccb31be2674d9fde184c5e5c54db368355b9984&
someone knows what i can do to fix the problem ?
What problem?
the red border "highlight switches at the bottom whe i switch in play scene
what are they made of?
And what does this have to do with code?
Seems like a #๐ฒโui-ux problem
those are images
I wanto find the vector 3 back of an object how do I do that
what does "the vector 3 back of an object" mean?
You mean the backwards direction for that object?
Yea
-theObject.transform.forward
Pretty much
Or to illustrate the point possibly better:
theObject.transform.TransformDirection(Vector3.back)
it works
you're doing something wrong
explain what you're trying to do, show your code, screenshots, etc.
Ok so im making a casing of bullets that fire so I instantiate them then apply a force to their rb. The direction is meant to be the backside of the spawner(intatiater obj)
ok then -spawner.transform.forward
then you did something wrong
I'll send a ss
your spawner is not oriented how you think, or maybe the things are colliding with something
etc
and what happened when you did that
It just gave the backward direction relative to the scene . Didn't change direction when I turned the spawner
You did something wrong then
your reference is incorrect for example
again please show your code, screenshots, etc.
Ok
Discord is being funny on my pc so I'll just send a pic from mu phone
Point is the spawner
why are there two different things
Also this is not what I said. to do
you wrote point.transform.position
that is not what I wrote
I named it weirdly but point is the orientation and firepoint is position
please copy the example correctly
Then why are you doing this
And this
Why are there threee different objects here
Ok let me explain
I have a 3rd person character that rotates according to the carma
Now in this player there is two points for instantiating objects
Fire pointsss and firepointss are the two spawn points
Your variable naming is absolutely painful
Ik it's just placeholders I clean up later
It's already causing you problems
clean it up now
to fix your code
Anyway have you addressed this part yet? #archived-code-general message
Point is the player orientation
Generally you should clean it up before asking for help from others, because it makes it extremely difficult to parse
because you claimed you followed my example and it didn't work, and it turned out you didn't follow the example at all
Okso what is your example
Are you just ignoring my messages? #archived-code-general message
I wanto apply the force to the rb backward to its relative position
Nvm I got it
I was being silly
yeah, you weren't following the example
I didnt read your messgwe correctly
so sad ๐ญ
code is cool at least
for generating mesh
Im Having an issue. With a Trigger collider of a game object with a certain tag. not returning in the player script. Anyone who could give me a hand?
Heres my code:
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public GameObject LootBox;
public GameObject BoxMenu;
void Start()
{
if (LootBox == null)
{
LootBox = GameObject.FindWithTag("BoxCenter");
Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
Debug.Log("GameObject: " + LootBox.name);
}
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Collision Entered");
if (other.gameObject.tag == "BoxCenter" && Input.GetKey(KeyCode.E))
{
Debug.Log("Opened Loot Box!");
BoxMenu.SetActive(true);
}
}
OnTriggerEnter is a single frame, so you are expecting to be pressing E when you enter
Try OnTriggerStay
the problem is. the debug.log isn't printing anything
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
credit: Digiholic
The one before the if statement?
yes
Alright, then refer above my post ;p
still, may want to change that to OnTriggerStay though
Just before going further, it's it a 3d or 2d game?
is it a problem that the game object with the player collider is a child of the actual player game object with the script?
Hey, I am currently having an issue with the OnTriggerExit2D and OnTriggerStay2D functions:
My game has an building system wich is why blocks can get destroyed. If these blocks have an trigger, the on trigger exit function calls, wich would not be a problem if not the on trigger stay function would stop being called. My current workaround is to execute the following code at the end of the on trigger exit function:
transform.position = transform.position + new Vector3(0, 1, 0);
transform.position = transform.position - new Vector3(0, 1, 0);
Is there an better workaround or a fix?
And are you using other layers that are not the default?
You
both objects need a collider, one or both colliders need to have IsTrigger selected, and one or both need to be rigidbodies
@gilded crag can you verify that you have this?
answer this to
verified
Good question, let's test it out
Ok so the heres my hierarchy:
the blue one is the one with the "is trigger"
The blue one is the one with collider
and Player has the script
absolutley nothing
it doesnt even print the "Debug.Log" i added
so something is wrong
Damn, and I assume, the player object has the rigidbody right?
oh
It calls the "ontrigger" methods on the parent or gameobject that has the rigidbody
In this case the body, but the body doesn't have the script aka nothing is called
Change either the gameobject in which script is or the same but for the rigidbody
It works!
That's good to hear!
||YOU JUST GOT DUCUSED||
||(A goofy character in the game)||
Hi guys, I am looking to send an instruction from one object to another using a string and some parameters, what i want the second object to do is call a function with the same name as the string and fill in the parameters, is coroutine my best bet or should something else be used instead
Love it
wait
i realised
that what happenes in the if statment can be done wether im in the trigger collider or outside
the collision doesnt matter
Huh
i don't have to be in the trigger area and click E to open the menu
i can JUST click E to open it
Looking fine
Thank you! made the song too
Huh
Thats some weird code doing that
Yeah ok that shouldn't be happening right? @gilded crag
I'm sorry, what is the original issue?
Heres my code ```
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float Speed = 1f;
public GameObject LilDevl;
public GameObject LootBox;
public GameObject BoxMenu;
public GameObject ShopMenu;
void Start()
{
if (LootBox == null)
{
LootBox = GameObject.FindWithTag("BoxCenter");
Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
Debug.Log("GameObject: " + LootBox.name);
}
}
void OnTriggerStay(Collider other)
{
Debug.Log("Collision Entered");
if (other.gameObject.tag == "BoxCenter" && Input.GetKey(KeyCode.E))
{
Debug.Log("Opened Loot Box!");
BoxMenu.SetActive(true);
}
} ```
The original problem was the the trigger collider didnt work at all. The NOW problem is that it works without the trigger collider
So you mean OnTriggerStay prints "Collision Entered"?
It's hard too read the console, there's too many logs click the collapse button
Yes, I do. This is redundant. What is your current objective?
to make it so. that when im in that big trigger collider. AND i press E that menu opens
I recommend this
Use a variable to manage if inside the trigger
And check for input in the update method
Aka (I'm on phone so beware):
bool inBoxRange;
Update(){
if(inBoxRange && Input.E) { openMenu();
}
OnTriggerEnter(){
if(collider is box) inBoxRange=true;
}
// your code goes here
I appreciate the concern
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float Speed = 1f;
public GameObject LilDevl;
public GameObject LootBox;
public GameObject BoxMenu;
public GameObject ShopMenu;
private bool InsideTrigger = false;
void Start()
{
if (LootBox == null)
{
LootBox = GameObject.FindWithTag("BoxCenter");
Debug.Log("LootBox set to GameObject with tag (BoxCenter) ");
Debug.Log("GameObject: " + LootBox.name);
}
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Collision Entered");
InsideTrigger = true;
}
void Update()
{
float Horizontal = Input.GetAxis("Horizontal");
float Vertical = Input.GetAxis("Vertical");
transform.position += new Vector3(Horizontal, 0, Vertical) * Speed * Time.deltaTime;
LilDevl.transform.localEulerAngles += new Vector3(0, 0.3f, 0);
//if (Vector3.Distance(LootBox.transform.position, transform.position) < 5 && Input.GetKeyDown(KeyCode.E))
//{
// Debug.Log("Opened Loot Box!");
// BoxMenu.SetActive(true);
//}
if (InsideTrigger && Input.GetKey(KeyCode.E))
{
Debug.Log("Opened Loot Box!");
BoxMenu.SetActive(true);
}
}
}
Yes
Now add ontriggerexit to set inside Trigger to false
Let us expand this. The boolean should be set to true or false in OnTriggerEnter and OnTriggerExit respectively. The GetKeyDown(KeyCode.E) should be checked in Update. Make sure Down is used to check for the button being pressed once, not continuously
@gilded crag
And:
yep
Yes, but add the if statement too
The Collider should be checked
Works perfectly