#archived-code-general
1 messages · Page 61 of 1
Looks more efficient. 🤔
just curious. Does it need to be more complex than something like this at this stage?
void Update()
{
switch (currentState)
{
case CharacterState.Idle:
// Code to execute when in the Idle state
break;
case CharacterState.Walk:
// Code to execute when in the Walk state
break;
case CharacterState.Run:
// Code to execute when in the Run state
break;
default:
break;
}
}```
at this stage that will work and I will do that, but I feel dirty doing that
but its the most practical solution for me right now
Isn't a sphere overlap more performant though? It's literally just a distance check.
What function should I use to create the sphere/capsule check? A [Sphere/Capsule]CastAll with no movement?
And you could even make it faster with a square magnitude comparison
@whole gull A couple of short, decent (?) video tutorials on FSM's to get started, if you care
https://www.youtube.com/watch?v=Vt8aZDPzRjI
https://www.youtube.com/watch?v=5PTd0WdKB-4
thanks!
Sure, a sphere overlap is almost certainly cheaper, but I would be more worried about the performance of the user code than the highly optimized physics engine, so I think fewer results for the user code to filter through will still be a win.
Ah, that makes sense.
Not sure what this has to do with C#. Make your image transparent.
There's a set of rules that a lot of programmers use called SOLID. In most instances where you use a switch statement, you're very, very likely breaking the O in that principle which is the open/closed principle. In this case, every single time you modify, add, remove player states then you would have to change the update method.
A more ideal way to setup a State pattern in C# is to actually use encapsulation to allow different states to have their own class and their own update method. So anytime you need to add a new state, you simply create a new class that inherits from an interface. That interface would force the new class to have an update method so there's no funny business and it's impossible to forget a step when implementing new states.
IE.
public interface ICharacterState
{
void Update(Character character);
}
public class IdleState : ICharacterState
{
public void Update(Character character)
{
// Code to execute when in the Idle state
}
}
public class WalkState : ICharacterState
{
public void Update(Character character)
{
// Code to execute when in the Walk state
}
}
public class RunState : ICharacterState
{
public void Update(Character character)
{
// Code to execute when in the Run state
}
}
public class Character
{
private ICharacterState currentState;
public Character()
{
currentState = new IdleState();
}
public void SetState(ICharacterState newState)
{
currentState = newState;
}
public void Update()
{
currentState.Update(this);
}
}
Now you can way more easily extend the character states when you inevitably add other things like jumping, crawling, climbing, shooting, etc
I have a couple hundred prefabs that I could either load dynamically through Resources.Load() or through making a prefab singleton with a Dictionary<prefabNameString,prefabGameObject> and loading them all at the start of the game.
When I load a prefab, I usually won't have to load it a second time and the amount of loading I do is pretty spread out. Also, the vast majority will not be loaded in a game as it is a roguelite. This is all due to adding scripts to my character dynamically.
Is one of the approaches strictly better or is it so negligible in my situation that it doesn't matter?
I think in your situation it's not a huge deal. I'd just do resources though since it's better for memory, only loading prefabs when you actually need it. If you were loading hundreds at one time then i'd change my mind possibly, but as you said, it's spread out.
Either way though, it's not like loading them all at the start is gonna increase the startup time of your game by very much, you could always benchmark it
Just mentioning, but you want to avoid storing things in Resources if you can, especially if there are a lot of them. But what you are talking about is more or less a pooling system. It's used a lot, and people swear by them (we use them sometimes). But when I've benchmarked it, the difference is pretty minimal.
Usually they come with colliders. And in benchmarking the slowest moment usually isn't instantiating a mesh to the screen, it's the initial physics check when it appears. So disabling/enabling from a pool doesn't help, as that check still happens.
But yes, a loading screen pooling the resources is common. Just keep in mind it also impacts garbage collection and memory use that way
Imho of course
I would say though, given your workflow, you could benchmark it pretty easily to see if it's worth it
Thanks for the great advice you two! I'm happy to hear that I won't have a big headache down the line if I maintain my current approach. Will definitely benchmark when most of the prefabs are finished.
Hi all! Today is the 3rd day as I'm trying to deal with zenject.
Such a question, if the projectContext itself automatically appears on the stage and cannot be added manually, which means I can’t just drag the necessary dependencies onto it, how can I throw global dependencies into it? Through delegates? What if the sceneContext is loaded along with the scene in the prefab?
My understanding is that Resources folder is actually lazy loaded these days.
I haven't checked it, but that's what I've been told. Apparently it's a fine way to do things. 🤷
oops, excuse me, it's still bad lol:
https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity6.html
I wish they'd just straight up explain how it works
Yeah, if you need to load something dynamically, you should use addressables
Instead of saying vague things like "performance degrades"
"makes memory management more difficult"
etc
Does anyone know how to get a list of triangles in a NavMesh?
Overall it's an outdated and lacking API. For example I think you can't unload the loaded assets manually.
Yeah, but does it load everything on startup and chuck it in a hashmap, or does it load from disk on demand?
For example
Not being able to unload specific assets is obviously a downside haha
Actually, I don't care about resources, I don't use it. Don't bother answering me, just a general complaint about the docs.
Beautiful, thank you! <3
Trying to write a function that will get an evenly weighted random point on a navmesh
No,it loads when you call it.
But I get what you mean. There was a way e of promoting addressables as an alternative to Resources and Asset Bundles. I wonder were all the info used at that time is.
Making a unity first person horror, I want my monster with ai to have a jumpscare, any idea on how I can make it so if you touch the monster the monster plays an animation and the camera zooms to the monster's face?
Add a trigger collider on the monster, when touched start a coroutine that:
- takes control of camera
- plays animation
- zooms in on face
- releases camera control
I'm good with animation of it but idk how to take control of camera
use cinemachine
pause FPS the script that is controlling your camera
switch to a camera that is configured as a closeup
yeah, that's good too.
But you'll probably want to freeze all input too
Assuming that's a thing?
Or you can just set a tracking camera that follows the monster's face with a zoomed FOV
Oh true
So I basically disable the camera script and make the camera turn to face the monster
If you're using cinemachine you can have a separate virtual camera for the monster facing thing
just parent that second camera to the face and activate it when you need to
put a higher priority
it should autoblend
interpolate the camera
like... slide it over to the position you want
Ohhhh ok ok
and zoom it etc smoothly
it's ok it just does smoothing for you transitioning from 1 camera to another
it can be adjusted
Cinemachine is really good, pretty much a must-have for most games
Hey guys! I just have a general question about unity. I've only just started but I want to make a VN with it. Is it correct to assume that if my game is sectioned into different segments like chapters that you can access at any point and in any order, I should use multiple scenes for each segment and then make a manager that allows players to start a specific segment/scene?
what is VN ?
Alright thanks guys
a visual novel
oh visual novel
yeah haha
different scene could be cumbersome but probably easier to keep track in terms of chapters
oh it would? I thought it would be as simple as pasting prefabs of a dialogue system and scripts that cater to a chapter. Is there an easier way of going about it then? Because I'm not sure how else players can choose to hop into specific chapters
I didn't mean difficult I meant you probably need to create a bunch but it's def easier to switch scenes and based on that you know where you are
ohhh gotcha. well that's a relief! thanks!
idk if this will help you but I made a game once with lots of dialogues and choices, maybe this comes in handy for you
https://www.inklestudios.com/ink/
never made VN though so idk what gameplay you need
Oh ink! I have played with it before and I love how it works with Unity. I was thinking of using this and either Yarn Spinner-- although the latter is something I haven't used yet.
Ink would definitely be enough for a VN though
yea! Ink is great they added a few cool features to run special code easier now without tags (old way) I never used Yarn tho , looks interesting as well
I only thought to try Yarn because Night In the Woods used it and I'm curious to see how I could replicate it. But maybe it's not the time to experiment haha
it's worth a shot
Alright, I'm now attempting to do a cone angle check, but I'm struggling to find the proper variables to use here.
In GZDoom, I would set this sort of function up for an angular check:
Vector3 PosDif = Vec3To(Mo); //Difference in position between inflictor and victim.
Double RelAngle = AbsAngle(Angle, atan2(PosDif.Y, PosDif.X)); //Difference in angle between inflictor and victim.
If (RelAngle >= AngThresh)
{
Continue;
}
(Keep in mind, in a Vector3 as defined by GZDoom, X represents forward/backward, Y represents left/right, and Z represents up/down.)
(Simply put, GZDoom's X equals Unity's Z, GZDoom's Y equals Unity's X, and GZDoom's Z equals Unity's Y.)
To get AbsAngle, all I'd need to do is get the absolute value of DeltaAngle (so, Mathf.Abs(Mathf.DeltaAngle(first_float, second_float)).
For finding the difference in position between the first and second objects (as I'd do with Vector3 PosDif = Vec3To(Mo); in ZScript), I'd just need to subtract both GameObjects' transform.position vectors from each other, correct?
Also, the Angle variable in there represents the caller's yaw (so it'd be represented by the Y-axis rotation in Unity).
While I'm at it, how would I go about making a pitch variant of this same check?
I need to know something about a piece of code: ``` for (int i = -rayCastAngle / 2; i <= rayCastAngle / 2; i += 5)
{
Vector3 axis = new Vector3(0f, 0f, 1f);
Vector3 direction = Quaternion.AngleAxis(i, axis) *-transform.up;
RaycastHit2D[] rays = Physics2D.RaycastAll(transform.position, direction, 1f) ;
foreach (RaycastHit2D ray in rays)
{
if (ray.distance < shortestRayDistance || shortestRayDistance == Mathf.Infinity)
{
shortestRayDistance = ray.distance;
print("srtdisray"+shortestRayDistance);
}
}
Debug.DrawRay(transform.position, direction * 1f, Color.white);
}```
Firstly, I want to confirm that the RaycastHit2D[] is only shooting one ray for every iteration of the for loop, each in a different direction?
For a cone angle check you can pretty much just do Vector3.Angle between transform.forward and and the actual direction to the object.
That's the result array. The thing "shooting" the ray is the RaycastAll call.
Secondly, if I were to use the direction variable in the if statement, would it be the direction in which the ray is shooting? Because if that is the case, wouldn't that mean that rays are being used in the foreach statement multiple times for each iteration of the for loop?
You are passing it in as the parameter to the Raycast so of course it's the direction the ray is shooting.
The Raycast only happens when you call RaycastAll, which only happens once (per outer loop iteration)
Yes, but I am using all the rays in the foreach statement, does that mean the first ray's distance is being checked for every itteration of the for loop?
You're calling your variable "ray" but it's a RaycastHit2D
oh.
but still, for each of the RaycastHit2D, would the distance be checked multiple times per frame due to the foreach statement being placed inside of the for loop?
Each RaycastHit2D is being checked once
Each RaycastHit2D in each Raycast. You are doing multiple Raycasts.
All the RaycastHit2Ds are being saved in an array right? The foreach statement is checking all the "ray in rays." Wouldn't that mean the entire array is being checked per iteration of the for loop?
You are getting a brand new array every iteration
They're not all being added to a single cumulative array
Wait so there's only one value in the array for every iteration?
No there's as many values as the RaycastAll hits
Ohhhhhhhhhhhhhhhhhhhhhh
But each RaycastAll gives you a fresh array for just that Raycast
Ohhh... I thought the collisions of all the RaycastHit2D per frame were saved in the array, thank you so much, that makes sense
I'll try that, thanks. 😄
I am trying to add a timer which runs outside the game onclick on a button. https://www.toptal.com/developers/hastebin .Thanks.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How would I find the actual direction to the object?
Vector3.Angle asks for two Vector3 inputs...
Shouldn't I just use their transforms?
the link is blank
Sorry. Let me create it again.
Here is the code url https://hastebin.com/share/aseyebiber.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
As in, transform.position?
GZDoom has Vector3's now?
Oh wait they have ZScript nowadays
Had 'em for the longest time. 😛
I'm too used to ACS 😄
what's the issue?
The timer gets reset when i switch scene or exit game.
store values in a file or PlayerPrefs
unless you persists this with DontDestroyOnLoad
I would personally use a file
it's quick and easy
scales up ok
Thanks
@warm mesa There's also a cool C# structure called TimeSpan that you could use to make the resume part more pretty. Could do something like this:
if (isPaused)
{
// When paused
pauseDateTime = DateTime.Now;
}
else
{
// When resumed
TimeSpan timeDifference = DateTime.Now - pauseDateTime;
TimeStart -= (float)timeDifference.TotalSeconds;
}
my indentation is fubar'd but ye
That's because the script is part of that scene, and the current reference is deleted when the scene unloads. You can do what null said, and call DontDestroyOnLoad on the script, or you can make a seperate MonoBehaviour for any information that must be persisted between scenes, and call said method on that instead. Assuming your script must be reset properly for anything else, of course. Alternative to DontDestroyOnLoad is creating a scene manually and to use additive scene loading. This gives more control, if you want that, which might be nice if you want to completely reset your scenes. Note DontDestroyOnLoad basically makes this seperate scene for you, which is quicker.
Hello, I have a problem where I want to find a point that lies on the intersection of a plane and a mesh a defined direction and distance from another point. I have made a simple illustration.
I have previously tried to use a MeshCollider on the mesh for something else and unfortunately the mesh exceeds the the collider's complexity limit.
I'm not sure how to start, any tips?
You want a direction not the position. B - A gives you the direction from A to B
So for Vector3.Angle, I need to pass transform.forward with transform.position - target.transform.position, correct?
The subtraction seems backwards to me
Just figured that out. 🤣
Switching that around made it work right. 😄
Thanks!
youre a fucking life saver cant belive it was that one damn small thing
Anyone knows how I can make the phone vibrate 1 tick when I click a button?
Handheld.Vibrate(); vibrates too long
I just want a single tick
I googled your issue, and found this link: https://gamedev.stackexchange.com/questions/177384/vibration-duration-for-mobile-devices-in-unity
An answer specified this script: https://gist.github.com/ruzrobert/d98220a3b7f71ccc90403e041967c46b
The answer allows a duration and it seems to work by calling the internal api or something
Note it's for Android
Suggest you just copy-paste the whole script, try it with some different values, and then strip what you want specifically, or keep it if you want all of it.
This is my "Building System" & i have a bug where it doesn't place objects on the "first clicked tile"
I have to run the mouse back over while holding it down to "place the item"
Placement Code:
void OnMouseEnter()
{
_highlight.SetActive(true);
if(buildManage.isEditing == true && Input.GetMouseButton(0))
{
buildManage.PlacePreset(_highlight);
_renderer.color = Color.clear;
}
}
Better Image
Thank you!
Glad you got it solved : )
Your logic is on an event of OnMouseEnter?
You should probably change it to OnMouseOver - which is called every frame, or OnMouseDown which eliminates the requirement to check for the Input mouseButton is pressed down, if you only want it to trigger on the first time you press and not while holding & dragging.
Ahhh thank you! That makes more sense to what I am trying to achieve as well haha
Is there a way to get a list of all currently loaded scenes?
SceneManager.GetAllScenes
it's deprecated
SceneManager.sceneCount and SceneManager.GetSceneAt
int countLoaded = SceneManager.sceneCount;
Scene[] loadedScenes = new Scene[countLoaded];
for (int i = 0; i < countLoaded; i++)
{
loadedScenes[i] = SceneManager.GetSceneAt(i);
}
No problem. Note that you're probably not the only person with the issue when it comes to questions like these. The answer I just gave you came from Google.
Google is very useful.
hey, sorry I'm a little new to bitwise operators since I haven't needed to use them before. If you have an int foo, why is foo & 0xffffffff not equal to foo?
It seems like it should return a value which is 0 where foo is 0, and 1 where foo is 1, right?
That's what it does
that's strange. That's not what I'm seeing here
when using foo & 0xffffffff I'm getting zero
You'll have to figure out why the value of foo is not what you expect
no, foo's value is correct
So, I'm doing this in HLSL, the operator should function exactly the same. I've got a set of pixels that I'm drawing as white if foo & 0xffffffff isn't equal to zero, and black otherwise. My actual code for this is this: Result[id.xy] = foo & 0xffffffff != 0 ? float4(1, 1, 1, 1) : float4(0, 0, 0, 0);
(I'd normally ask a question like this in #archived-shaders but I'm asking here since most languages, regardless if they're shader or not, have a bitwise &)
Anyways, this yields all black pixels. But if I just write Result[id.xy] = foo != 0 ? float4(1, 1, 1, 1) : float4(0, 0, 0, 0); instead, I get the white pixels I was expecting
The precedence of & is lower than != so your code is equivalent to foo & (0xffffffff != 0)
And today I learned this x) cs unchecked((int)0xffffffff);
@everyone Hello. It is possible change banner ad for something else via script ??
Attempt to ping everyone, so close to 100000 people. Don't do that, fortunately it's disabled here
What is a banner ad and how do you show it?
I am using standard Unity documentation: https://docs.unity.com/ads/en/manual/ImplementingBannerAdsUnity
Considering the banner shows an ad, I don't think you have much control on what shows?
I don't see any method specific to setting the content, anyway
How can I make my own ad?
No idea and that kind of goes beyond the scope of these channels
Maybe just a button that opens a link
If you dont need it monetized or anything
I do not understand. Why button? What link?
Nevermind. Not sure what you meant with your own ad
Here you don't have the word on what ad it shows, because Unity's controlling it. The advertisers reach out to Unity, which then dispatches the ads to the game.
If the advertiser reached out to you directly you'd have control on what shows, here you don't.
Hi! Is there a way to call a method by clicking in <a href> in console?
anchors work in Unity?
Or is your question how to simulate the anchor tag?
Is there a general design pattern that is applicable when you want two objects A which contains collections of B and you want B to do some general operations on A?
I understand it's achievable via either Singleton, but that's a poor fit in this case and directly passing the reference of collection A to all instances of B, but if I'm going to do that, might as well have the functionality present in A which manipulates B. Any other alternatives I can read up on to see if they might fit?
no, seems like I wasn't clear. I've found useful docs here https://docs.unity3d.com/ScriptReference/EditorGUI-hyperLinkClicked.html
Very generic. But you can abstract the dependency if you want with some interface, use callback method or events.
huh interesting, I've never seen or used that before. Seems reasonable to assume you can call a method from the event.
If what you're asking is whether you can call methods dynamically from attributes on the link, the answer is yes. But you'll need to use reflection.
So this works, right? Subscribe to that and HyperLinkClickedEventArgs will contain optional arguments.
guys i have a problem
this IEnumerator broke after i set active it to false
anyway to wait script?
What broke?
this IEnumerator
And I think yield return null is better. It will wait a single frame.
But what broke?
it will not run after i set active to true again
scripts xd
You need to manually start it up in OnEnable
alright
thanks this btw
thank you
damn still
You should Debug.Log your steps and check what plays, or not
Check if it restarts, and if the coroutine is running
i checked
after i enable it again it still not run
Did you verify that OnEnable runs?
Perhaps you can share your code?
lemme check it
wait a bit
Please share your !code like this 👇
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
So, does the the console log 2?
yes
wait a bit ResetOptions() still run when outside an if
There's a lot wrong with the code. Do you want this to run for a long period or just once?
Because currently it runs once and not again
oh after yield return new WaitForSeconds(0.1f); not running
Then it must stop?
which line you mean
yes
The whole Coroutine
Perhaps change your ResetOptions method to this, and test it again:
private IEnumerator ResetOptions()
{
while(true)
{
yield return null;
if (m_requiredDropdown == null)
{
continue;
}
if (m_requiredDropdown.prevValue == requiredDropdown.value)
{
continue;
}
Debug.Log(requiredDropdown.gameObject.name + " Changed Value");
Set();
return;
}
}
alright
This runs until m_requiredDropdown.prevValue != requiredDropdown.value, then calls Set, and then stops.
understood
A while loop runs as long as whatever inside it is true. Since we literally pass true, it runs forever. Just make sure to add some delay or you break your application (which is what yield return null does). return; makes sure we stop the loop. continue; resets the loop.
well return; will not work in IEnumerator so i need to swap to void eh?
Change it to yield break;
My mistake
Or change to break;, which will end the while-loop itself
No, yield commands only work in IEnumerator, IEnumerator<>, IEnumerable or IEnumerable<> methods
Considering Unity's Coroutines work with IEnumerator, it works here.
oh damn its not work
What does not work exactly?
after value changed Set() was called
yep
That's what you wanted, right?
Put Debug.Log($"{m_requiredDropdown ?? "N/A"}: {m_requiredDropdown?.prevValue ?? "N/A"} == {requiredDropdown?.value ?? "N/A"}"); above the first if-statement and test what it returns
alright
Take the edit. It will display "N/A" for no value
As some point it should show values. Otherwise something is wrong. You can verify that way if you actually get the proper values
uhh does it really need 2 "?"
What do you mean?
Lame, then just test with Debug.Log($"{m_requiredDropdown"}: {m_requiredDropdown?.prevValue} == {requiredDropdown?.value}");
Hello guys, I would like to assign some GameObjects to 4 prefabs that I created while the level of my game is running: since it is a procedural level the GameObjects should instantiate into my prefabs script, I did it for the player with "GameObject.Find("Player_Mobile").GetComponent<Transform>();" and it works, but for the other gameobjects it doesn't work
They are different GameObjects to assign to the different 4 prefabs but everything is on one script only attached to the 4 prefabs, how could I do that?
Also, put it above the first if-statement, not inside it
ah alright
I tried to use the GameObject.Find("")GetComponent<>(); for the other GameObjects that I need but it doesn't work at allù
well requiredDropdown is not null and
when i changed value
So that means that they're both the same
ye but set() still not called xd
Because there's no change
Now when I look at the code they share some resemblance, so perhaps they share the same value?
So if you want to call set() when it changes, why not make your own variable?
private int _previousValue;
private IEnumerator ResetOptions()
{
while(true)
{
yield return null;
if (m_requiredDropdown == null)
{
continue;
}
if (m_requiredDropdown.prevValue == this._previousValue)
{
continue;
}
Debug.Log(requiredDropdown.gameObject.name + " Changed Value");
Set();
this._previousValue = m_requiredDropdown.prevValue
return;
}
}
Something like this
Or figure out why m_requiredDropdown.prevValue is not actually the previous value. Perhaps it changes the next frame?
Lets ask a whole different question: why not do all of this in an Update method? Perhaps it works there?
ah i forgot to mention this is InspectDropdownManager.cs
i called it self
hmm im still not understand it but somehow it worked
thanks my man
im going to figure it out
oh understood
Will a method finish executing even if the root GO is disabled? Just as a basic example, will this log?
gameObject.SetActive(false);
Debug.Log("I am inactive");
Yes
Scripts don't stop like that
"Disabling" objects are purely for Unity, and Unity specific methods like Update
Assumed not, just wasnt on PC atm so couldn't write it up
I never know what magic Unity does behind the scenes to make C# things behave in unexpected ways, so 🤷♂️
#↕️┃editor-extensions may be able to help
Alright, will ask there, ty.
the snippet you showed will always log. however, when you deactivate other objects, what really happens to the scripts attached to those objects is sensitive to where you are in the player loop (FixedUpdate, Update), script execution order, whether or not the code is in a coroutine and what object is hosting the coroutine.
you should use object active / inactive for
- rendering, where showing something for 1 extra frame doesn't matter
- time insensitive gameplay logic. for example, you can represent the active improvements on your Puerto Rico board as game objects; the contents of your inventory in an RPG; a building in your city sim
- user interface elements
you should carefully use object or script active/enabled for
- time sensitive gameplay logic. for example, you should not use it for hitboxes in a realtime shooting game. people do, and because they are not really aware of the player loop or script order in a sophisticated way, they have all sorts of bugs, like "ghost shells" in a tank game a user once asked about here.
- tightly coupled things like singletons. game controllers, accounts management, etc.
I have two ints, i wanna check if any Bit from the first int is present in the second int. If thats the case, return true;
E.g. 11001,10001 -> True (since the first and last bit were set in both)
How exactly do i do that? I always was bad at logical operations...
Oh wait, thats a & operation... isnt it?
But how do i check it then, if the result was appropriate?
Ah alright, thanks 😄
Is there a way to deal with these domain reload times whenever I change a single line in a script? I thought that by using assembly definitions it was supposed to only recompile that assembly, but its like the entire project gets reloaded and using the Editor Iteration Profiler is not really telling me anything useful. I have a pretty simple project with basic 2D and URP packages on 2022.2.6f1 with VS 2022, and basic scripts that don't reference any packages in their own assembly, and it takes 15 seconds to reload domain when I modify a script, why is this a thing now?
Checking for > 0 is actually an error since if only the highest order bit is set, it'll be negative.
The correct way would be:
if (a & b != 0)```
Great, thanks 😄
And what if i have two different sized arrays of ints? Like large bitsets? ^^ Is it the same procedure?
ahh right, typically you use uints for bitmasks
E.g. : 10101,10111 and 10101,10111,11111
depends on how youre trying to compare these
quick question, I have a message that I need to send in a webrequest, I want to change it to a link format (for example spaces will become % ) ... can someone point me in the right direction, I dont know other examples than the space one
you cant really do (array1 & array2)
you'd walk the arrays and compare correspending bitsets
i believe this is the game you received from someone else
that's what you said earlier
right?
you're working on this with someone else and you were trying ot understand what addressables does
what's your big picture goal?
put your cursor over the first red line (in Start()) read the error message.. what does that say? -> Fix it
Probably missing a using namespace. But you've also got some basic syntax problems going on.
yeah what are your goals?
you're jumping right into stuff it doesn't look like you know quite yet, but you can learn it
it looks like you haven't used C# before
anyone that can answer this question please?
its because they are giving me programming jobs but im a 3D artist so....
if an asmdef references other asmdef's .. they get recompiled too
lol gotchyu
okay well what is the big picture goal? like what ar eyou being asked to do
yet you chose the programmer role on here ;p
managing memory for a big scene
no clue lol we have barely any assets in the scene lol
idk what's the point of doing it now
okay
Im using addresables
i mean your brain is in the right place
you know this is stupid
so here's what i suggest
i tried removing dependencies but it didn't change anything. Does your answer mean that normally it should be very fast if i change a script in a small assembly def?
delete the files that you created that are immediately causing hte game to not even compile
don't do that
don't do anything where you are put immediately into jeopardy
you can delete this whole file because it isn't going to do anything for you
no, not necessarily. asmdef's can speed up compile time, but they can also slow it down if not done correctly
it's going to undo things for you
like it will break things in vague ways
even when it compiles
or just add the namespaces required and move on
my suggestion is to create a script called MemoryManagement, a default one with Start and Update
deleting this class might cause other issues if it's required by other clases..
Seriously, just fix the very fixable errors listed in the console
and write // todo: implement memory management into it
you can have it print some stuff. but since this isn't a problem that exists yet, and you don't know how to program, you wouldn't be able to tell if you were doing "it" "right" anyway
you can also create a visual scripting thing
which will be completely opaque to your colleagues
and focus on something high yield for yourself
Yes, lie to your bosses and coworkers \s
you shouldn't use addressables
im just trying to figure out if 15 second reloads are normal or not in this version of unity when there is really nothing fancy going on as far as i can tell
@swift falcon are you guys using git?
it's easy to make your project compatible with the new reloading approach
i am using it now, and i have complex native plugins
na PlasticSCM
okay, that's good
Fanciness isn't the deciding factor on how long it'll take
- Size of project (how many classes)
- PC spec
Probably other stuff that I'm not aware of too
do you have a screenshot of your scene? or maybe of the assets you've made so far?
er..
and can you maybe give a super brief description of what the game is? like a logline? just so that what i am saying, i know it makes sense?
Can I send you the screenshot tru dm
i started the project last week, there's barely anything in it, just a simple 2D URP project with the basic packages, burst is in there, i tried turning it off in case that was it but it didnt change anything
try this
it's in your Project Settings -> Editor rollout
this is what i'm talking about
yeah im talking about modifying a script, i have that set already
I haven't touched 2022 yet, I stay away from tech stream versions unless I absolutely need something that's only in the tech stream version.. no idea if 2022 has longer recompile times atm
then you're in a lot of jeopardy if this is project is empty and it's so slow
it's true you should probably use 2021 LTS
it's hard to say. what is your game? what are you trying to do...
are you on a mac by chance?
im on windows, ill try going to LTS, its just a basic prototype at this point
since when is 15 seconds to recompile astronomically high? relative to nothing maybe its a lot but unless your changing minor things constantly
@swift falcon you're at 1/3 through the beginning-middle of a journey, multiple journeys, at least 12 of being talked at in circles
also, i did import fishnet at one point and removed it, maybe it was the cause and removing the asset kept "leftovers"?
mine is quite often already compiled by time I get from Rider/VS to Unity.. if that was happening to me, adding 15 sec to 0 is quite the jump 😄
when i was using unity 2018 i was not getting these issues at all
@swift falcon i guess you're learning the most important lesson of all
15 is not that bad but i imagine as the project grows it will get way worse
there aren't "leftovers". Assets are generally only in 1 folder, deleting that folder removes everything. If there are any assets left over in eg: Resources, then they'll be missing files and not cause any issues anyway
if you're being asked to do something that makes no sense, and you're confident it makes no sense, you can focus on doing what you do well (3d modeling) or if you want to learn to program, if that is the goal, focus on a programming goal that's fun for you to do so you do it every day without stress
even if it's hard
i dont know if this gives you guys any information that could help but i may as well post it
addressables doesn't sound that fun to me personally
Have you gone from 2018 -> 2022? They made a change at some point in 2020 or 2021 which just shows compiling that was hidden in previous versions, and they say hasn't made any difference to the compile time but just brought it into view
yeah i was working on a voxel engine for 3 years in 2018 and it was not even getting close to 15 seconds
do you have windows malware defender enabled? and is your project in a google drive, dropbox, network share or similar?
hmmm I guess I'm doing something wrong but I don't find myself waiting for it more than a few times a day since ~~mist ~~ most everything I might want to tweak is a variable in the inspector. I guess I could adapt my workflow if I knew for sure it would always be 0 🤔 something to investigate perhaps
ohhhh do you think an antivirus is making the files appear modified??
Modified? No
and no sharing for this
you can disable the malware defender realtime monitoring by starting an administrative powershell and running Set-MpPreference -DisableRealtimeMonitoring $true
but don't.
you can also do it in control panel but i don't remember how
from a practical point of view, the realtime monitor causes unusually high performance penalties for developers
you can always turn it back on if it doesn't improve anything for you
right now odds are it's that your computer is slow
Set-MpPreference might be a windows server cmdlet and not work on windows 10/11... so forgive me if that errors out and doesn't do anything
ah so you think its just using CPU, i doubt that's the case since it was doing fine on an older version of unity, my CPU is probably 3-4 years old i dont remember
you just have to be trying this stuff a million times faster
instead of writing here lol
im pretty sure its already turned off but i guess i could try, seems like a weird attempt
well you can punch it into google and read all about it
Quite a basic Q, but my architecture fundamentals are terrible and I'm trying to build better habits:
I'm trying to stray away from using frequent singletons in my projects and find myself often struggling for alternatives. In my current situation, I'm building a roguelite deckbuilder & when the player starts a new game a RunContext is created. This is a plain C# class that needs to be injected into various other classes & monobehaviours. What are some other ways for dealing with common dependencies like this? I've played around with DI in Unity and I'm not a big fan, and service locators just feel like singletons with extra steps.
Well, a singleton is a very valid answer to this. There's nothing wrong with them
I would suggest a GameManager that holds an instance of your RunContext
You can then delete that reference when you restart the game
i'm putting my money where my mouth is and trying a lot of my own recommendations for my own game
right now i simply pass the context down, since it's the least ambiguous
GameManager itself holds no data but references to data, like that
And it can end the game etcetera
it's verbose but i couldn't think of a simpler alternative with fewer surprises
i am also using interfaces to have the same object (a RunContext for example) but only permit the user of it to do limited things
this is what I'm doing, and it's already feeling so bloated. Some constructors are awful:
public NeedsDependencies(BattleContext battleContext, RunContext runContext, PlayerContext playerContext, ...)
yeah
i actually put this all in one object, Context
and if the method needs to only know about the player's position and the battlefield objects, the object that method is passed is an IMethodNameContext : IBattlefieldContext, IPlayerContext (c# doens't support & on interfaces)
This is what I've done in the past, but things end up there simply because something else needs a reference, even if it doesn't belong; and I end up with a manager of unrelated systems and contexts just for the sake of access. Big red flag
You should not use constructors in MonoBehaviours. Maybe you want to look into this: https://github.com/Mathijs-Bakker/Extenject
That was just an example of a plain C# class, ofc I don't
Well either way, that project implements dependency injection into Unity
So you can pass your context down with it
yes
I hadn't thought about this, this is actually pretty neat.
i'm writing this with other people authoring cards in mind (this is like Clash Royale)
made good progress, today is day 4
This is the same reason I've been agonising over the core engine behind what I'm building. Decided to shelf that idea and wait until I'm a more experienced programmer 😅
https://appmana.com/watch/battleblocks day 1 prototype
Destroy the enemy castle!
as you can see this is multiplayer
not sure if you're in my match
Hahaha, that's great
quality dropped a lot
I think so
so i'm testing all these ideas now
here we go
✅ networked multiplayer ✅ plain unity physics ✅ perfectly synchronized ✅ test easily in editor
cool
✅ works since day 1
Would you be interested in me sharing the repo for my current WIP with you? 😄 I'm very early days so there's not an awful much to go through, and I don't expect you to fine comb it - but I'm trying out a lot of your recommendations that I'm not used to (UniTask, prefabs > scenes, custom game event loop), and I'd like to see if you think it's coming along or if there's any screaming red flags with my approach
im kinda jealous tbh. the most ive done with "networking" is leaderboards
a simple multiplayer from the ground up project has always been something I wanna do but its so boring and unrewarding feeling I never get through the wall
i feel you, i recently tried the same. there's a lot to unpack with networking and it's very intimidating. i would say stick to it and you'll get through slowly - but I ended up quitting, so 🤷♂️
you can do it too
appmana sdk is free
and i don't have a way to collect payment
local multiplayer game --> networked multiplayer
ive got as far two FPS players that can kill eachother but it was bandaided onto another project and was full of bugs
sure i'm going to open source this soon anyway
gotta remove rayfire and some of the paid assets
but otherwise there's nothing sensitive about it
cool. are you going to accept commits?
thanks, that's very appreciated. Going to spend a bit of time today cleaning up/commenting some stuff. I'll DM you a link later?
i have a script that selects the closest vertex to the mouse position, i wonder how can i select the faces this vertex belongs to?
or how can i select a face (its four vertices) of a mesh?
yep that's the idea
same as spellsource
clash royale except community contributed cards
and i don't think you'll have to be an engineering genius to do it
if it works in editor it'll work multiplayer
the naive solution is to find the face in the triangles array using the index of the vertex, im not sure how youre getting the vertex though and this might be pretty costly, i feel like there might be a better solution
there will be multiple faces that use the same vertex
very cool. im interested for sure. feel free to DM/ping me when you feel its ready 🙂 @polar marten
right now i have a distance function and it returns the closest vertices within a radius.
I need it to be more like a tile selection than a circular brush.
Its for a tool so performance isnt really an issue here.
how can i do it with triangles so i can get the full face? i guess itll be 2 triangles
so youre raycasting onto this mesh and iterating through the whole vertices array? is this a flat plane that you know the order of the vertices and can determine their position by their index without looking it up?
yeah exactly
is it a heightmap? as in, the vertices only change in Y direction?
well im not so sure about the last thing, because the vertices array isnt in any particular order is it?
exactly this yes
guys can someone tell me why an https request isn't working when I send a unity web request
after reading i found out about this class CertificateHandler
i basically want the tool to select faces in square (1x1, 2x2, 3x3) instead of vertices in a radius (it misses the corners)
but i dont know how to use it
theres a lot of different ways to do this and its hard to say whats the right way for what you want, if you want a really fast/hacky solution you can probably check the X and Z values individually to have a "square" effect away from the click point, instead of a circle "radial" effect
so instead of using Vector3.magnitude, you check Vector3.x and Vector3.z individually
i think that may do what you want based on what you said, but if youre looking for more refined functionality you probably have to implement a grid system
i see, thats some insight.
im gonna look into those, thank you.
then getting the face is just finding the vertices' index in the triangles array
yeah lots of exciting stuff to try that clash royale cannot do.
- what if you could summon a little war cart, and summon archers on top of it? it would literally be a unity vehicle
- multiple 3d levels of units. navmesh pathing over an actual castle structure you start building with ramps. instead of attacking the walls, enemy soldiers would path to a "softpoint" inside the castle, up some ramps, attack that, and when it dies, the whole castle crumbles
- a literal flood (obi fluids)
And what's the game?
ya clash of clans is terribly simple but I imagine that is a lot of the appeal. it could use a lot more juice IMO
Rayfire for the destruction or ?
Nice game 👍
I think this conversation is better suited for #💻┃unity-talk
Application.isEditor or use #if UNITY_EDITOR
Do you need to [ExecuteInEditMode]?
Honestly, your check should work. Probably something else going on
You didnt mention it was a ScriptableObject...
Hi. I have the following code snippet: [SerializeReference] private List<Node> _nodes; inside of a ScriptableObject. However, after adding the [SerializeReference] to that so I could preserve types, Unity crashes (no error message or anything) immediately when I try to play my game. I have no clue what's happening lol
sounds like you might be abusing ScriptableObjects. What are you trying to do with them? @round kelp
yeah, this sounds not good. But you could always ClickEvent -= UpdateProgress; right before.
OnDisable?
well, OnDisable gets called right before OnEnable for ScriptableObjects, so basically the same
You might have an infinite loop in your code dealing with that list
This is pretty standard practice actually
It is more proper if they would destroy the SO for some reason though^^
Hmm. Idk why that would suddenly appear after adding the Serializable thing
Yes, I know. I was saying the way they were using SO sounded not good.
Because you have code dealing with that list perhaps?
Yeah I was kinda responding to @round kelp saying it seemed abusive
Idk. I'll have to check it out when I get back to my computer. My only thought is some recursion oversight because anything dealing with the list functioned fine before allowing node types to be preserved
I am trying to make Client Side Prediction with RigidBodies, i made a system that creates a empty Idle Scene at runtime and places all players in there, when it's time to simulate the movement it moves the selected player to the physics scene applies the forces and does GameManager.Singleton.simulationPhysics.Simulate(minTimeBetweenTicks) simulationPhysics is the physics scene, but the problem is when i simulate it also affects the Idle scene
How can i stop the Idle scene from being simulated
Does anyone know any classes that are good for beginners? Mainly online classes
Brackeys
Codemonkey, kiwiCoder, brackeys & Dani
same thing with 1 less axis
Setting Inspector Values?
Fixed it by setting a localPhysics mode parameter when creating the scene
Help Me With 2D Please!
Does dani have classes/tutorials?
he has a tutorial channel too, but you can learn a lot with his videos
btw do you have anyone who doesn't use assets from the store? I wanna learn from scratch, but I went through the 2D tutorials and it didn't have much
I'm not sure if I'm not seeing something or looking hard enough, but a lot of the tutorials that have that basics in it seem to have store-assets
that's because putting together a tutorial focused on the code is easier if you don't have to make the sprites yourself. you are incredibly unlikely to find a tutorial that shows you how to not only code but also how to create your visual assets because those are two completely different skill sets
do you know anywhere that I can find online classes maybe?
kodeco has good written unity tutorials
I'm kinda lost when it comes to trying to learn where I can find tutorials
otherwise you probably want to use the unity learn resources since they are free
does he use store assets? Or does he have videos that explain how to create sprites and all
when you say how to create sprites
do you mean like, artistically?
the tutorials will cover tech art
why can't you learn how to create sprites from one person then learn how to code from another?
but not drawing
As in being able to put a character made from gimp for example
that's tech art
which will be covered in some tutorials for unity
however, nobody uses gimp
oh lol
so that's going to be more rare than say photoshop, which unity has a specific importer for characters arted in photoshop
you can save a psd in gimp, i'm sure, and it's the same thing
and you can learn from a photoshop tutorial how to do something in gimp
in the same way you can watch a maya video and learn how to do something in blender
ok
thanks for the suggestion
do you know any specific videos that are from him? Like those that help with creating maps & coding characters
no but the written stuff is really really good
it's all written
it's not videos
that's why it's so good
hmm
i think the first thing you should learn is google
also, if you want to program, you better get used to reading things extremely carefully too
not just tutorials but messages on chat lol
got it
tysm
the last thing i'll say is seriously, stop with the videos sooner rather than later
I was getting really confused with them
so I think I kinda had to
I feel like whenever I watched tutorials, I always ended with more questions than answers
And I never could remember what I "learned" from them, no matter how many times I watched
Im using my microphone In unity but its not picking up the right one how can I change the microphone in the unity editor to the correct mic?
Microphone.devices // get the name
Microphone.Start("yourDeviceName", true, 10, 44100);
cool I will try this thanks 🙂
Can you run and dispatch compute shaders in an async task?
hey,
do List<> s reorganize themselves after removing one object?
for example : if i have a list of (10) counts and I decided to remove the first item list.RemoveAt(0) .
would item of index (1) became item of Index (0) ?
They wouldn't get organized. They just wouldn't get unordered. The first element would be removed and index zero would start at where the second element was.
Could always read the doc or quickly test it yourself
When you call RemoveAt to remove an item, the remaining items in the list are renumbered to replace the removed item.```
Thanks ❤️
I have a chicken that I want to animate in a 2D game and almost got it working. I have two blend trees to switch between walking and idling animations, but for some reason, only the walking animation plays.
Here is my code, it's pretty short:
https://pastebin.com/7SLprW2y
I think the problem may be linked to the animMoveMagnitude as it stays at 1 and goes up to 1.7 when moving. The condition for moving is if its over or under 0.1
The node setup for the animations are set up correctly, the issue relies in the code somewhere.
Edit: Problem solved! I changed the animMoveMagnitude to rb.transform.magnitude
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.
Anyone using vscode over vs for editing scripts?
Curious if the vscode integrations are as ergonomic / reliable as visual studio
Unity no longer officially supports the VSC plugin. It's written somewhere here, can't remember where, probably in the #854851968446365696
Interesting
Thank you
wow, that was fast
Haha
@winter bramble if you have the income to support it, I would suggest trying out Rider on their free trial. it's a very nice experience. I use VS at work and have done for the last year* - still prefer Rider
Oh cool, well I do love jetbrains stuffs. Might consider it - thank you.
Hey guys, just a thought, but where did you guys learn to code? From Youtube, coding classes, where? I'm trying to figure out where's a good place to start to code, I already have a few sources, but I'm trying to see if there's more that are good.
hey ,
should I force close the program or wait ?
everything is saved, and the scene is very small usually takes less than 5 sec
do you happen to have any infinite loops or recursion happening in an object's Awake method
yes , i have a while loop , could it be the reason ?
if the loop doesn't end or if it isn't in a coroutine with a yield in it, then probably
oh thanks for the heads up , i'll double check the code then ❤️
In ECS, do you still get the same performance boost when using references instead of direct value types inside of components?
no
is your name supposed to be after the chip manufacturer? EG the Zed 80?
belay that... that's zilog =/
So I'm confused how the hybrid ECS works. You still use GameObjects, but there's like a proxy to sync the struct values with the actual GameObject's transform. Isn't this still slow? Because the backend still has to find the actual GameObject in non contiguous memory?
You're only using GameObjects for authoring. Once it is baked, your GameObjects become entities and your Monobehaviours become components. There is no syncing back to GameObjects.
I'm talking about the hybrid approach.
If it exists, the transform matrix in the LocalToWorld component of the entity is copied to its companion GameObject’s Transform. Those GameObjects are always in world space, the transform hierarchy only exists on the ECS side.```
Ah I see. Sorry, I havent been in .17 in a while and assumed by hybrid you meant gameobject authoring.
I think that docs page answers your question though. There's no performance benefit to using Hybrid components over GameObject-Component architecture.
attempting to implement a "shrink" powerup in my unity game that scales down the player when used for a limited time, but if the powerup ends while theyre in small spots theyll get stuck when going back to normal size, any thoughts about workarounds to un-stuck them? i could make all small spaces unaccessable but that kinda defeats the point of shrinking i feel
not using rigidbodys if that changes anything, character controller with capsule collider
Sounds like a game design question to me. You could kill them and make clear that they'd better get somewhere safe when shrink mode is about to end
thats a good thought 🤔 might do that
Tl;dr: I need to make a physics engine without collisions, the unity physic engine is not useful for what I am trying to do, does anyone got experience making them?
Unity keeps resetting my object's pivot - does having an animation on the object do this?
Nothing else on the object, just the basic stuff + animation
What exactly do you want it to do then? Collisions is a major part of the whole physics simulation.
You'd need to detect collisions and when movement gets restricted, you need to physically move the sprite manually into a viable position
Assuming your animation changes the local position of the object(and by pivot you mean a local position offset), then yeah.
i do like the idea of suffocating them or something like in minecraft
you build a block on your dome, you sufficate 😛
I mean the animation just rotates some bones, doesn't actually move the object's position if you see what I mean
I know fuck all about animations so
I'm trying to make a simulation of linkage mechanisms, for this right now all I need is rigid shapes being connecting with each other with rotation joints and to fixed points, being able to apply a force to any of them and the rest to react properly
Basically just as if you were using the hinge joint 2d
I tried using it already but it freaked out super quickly so, yeah
If it really just rotates, then it wouldn't affect local position. But you didn't provide much info so I was even thinking about 2d animations.
Well, simulations like that are pretty complex and sensitive. Sure, you could just code it all without relying on unity physics, by only adjusting the link object positions.
yeah, but I am not looking to make it just appear realistic, I need the simulation specifically so I kinda need to code physic system, so yeah, I know you might not be able to like tell me step by step, but any resource could help me
Well, using unity provided components would be the easiest solution, but you could implement your own simulation. It shouldn't be too complicated, you just need velocity and position parameters for each link as well as references to the connected links. Then you just simulate each link every frame by applying forces(like gravity) to velocities, constraining the velocities such that the links are maintained and applying the final velocity to positions. For a more or less realistic simulation, you'd probably need to make several iterations of simulation per frame, as each link will be moved and adjusted several times.
For more technical/academic info, try searching "rope simulation" or "rope tensions forces simulation" or something.
Thanks, much appreciated
Vector2 size = new Vector2(transform.localScale.x * colliderSize.x, 0.001f);
RaycastHit2D[] results = Physics2D.BoxCastAll(start, size, 0, Vector2.down, Vector2.Distance(start, end), layermask);
there should be incorrect on Vector2 size because transform.localScale.x but if scale is 1. it shouldn't have any problem
with this 2 line of codes, it mean I use the box to find object by drag it down, right?
and with size.y there shouldn't be hit.point that is higher than start.y more than 0.001f, right?
but this is the result
it'll get the result like this when it near the wall
unit y is start.y
@formal dust Maybe Debug.DrawLine from start to hit.point, so you get an idea where it is detecting the hit
Not sure if the 2D BoxCastAll detects hits that initially overlap the box or not.
sorry
I send the y that doesn't have a problem
red box is area that this boxcast go from start to end
The axis in the image is y=0.01520102
when I move out of the wall it work correctly
like this 1
Morning, is anyone able to help with a problem I'm having with configurable joints? In short if my parent object is sat at 0,0,0 its fine. But the further I move it from zero the further the connectedAnchor moves out of position. Here's a short snippet
Given an index how could I get a point in a square spiral? Certain there must be a simple solution to this. The closest thing i could find would be this desmos graph: https://www.desmos.com/calculator/20cexqlcyy but sadly i don't speak math, so i don't know how to convert it into something useable
One question about grouping your codes.
Do you prefer to group them like UI, Core, Data, etc.
All UI scripts in UI folder/namespace, etc.
or first categorize them component wise
MechanicA/Core,MechanicA/UI
MechanicB/Core,MechanicB/UI
For example for inventory.
Gameplay/Inventory/UI, Gameplay/Inventory/Core.
I mean you consider first layers (it is a UI script, service, core, data, etc.) or first split them into components/usecases
I got to a point where I just dumped all my scripts into one folder cause I couldnt bother navigating them all
I keep SO data separate though
Both are pretty good ways of organizing your assets, I think it depends on the scale of your project - if it has a lot of features/game mechanics, grouping all the assets related to that mechanic may be a good idea to make it easier to find the assets that mechanic needs to reference
If you have a larger scale project, where multiple things share multiple assets, and your project may be largely managed by the design and art team, it may make more sense to have assets grouped by type so its easy to find general assets and prefabs, but could make finding certain assets require you to use the search bar more and remember names - that said, I personally prefer the first option for the scale of projects I make as I find it helps keeps me organized and know that every script and asset has a place thats easy to navigate or even move out the project, knowing I took all dependencies with it
can someone tell me the representation of a string that has two return presses* after each other ... like "\n\n"
I need to know to solve the current problem
"\n\n"
I tried thaat... it didnt' work.. I was trying to replace it with "" (delete it) but it didn't work
Either the string doesn't contain what you think it does or you're doing something wrong
I have the file ready and it has only returns
i will check for spaces but i dont think there is
Depending on the platform newlines can be represented differently. \r\n is the windows newline (CRLF, carriage return + line feed)
didn't work
hmmmmmmm ok i will see that
also didnt work
is there a website that I can put the file in and it will give me the values \n or \r or something else
is it possible to reference a prefab from a script attached to that same prefab? when I drop the prefab onto the field in inspector it references the object in the scene instead of the original prefab
Sadly no
Debug.Log(str.Replace("\n", @"\n").Replace("\r", @"\r"));
I dont know what you did in there can you explain
what's @"\n"
Replace newline and carriage return characters with literal text \n and \r so that you can see them
@"\n" is "insert the literal characters \ and n, not a newline character"
AAAAAAAAAH Thank you... now this is what I got as a debug "\n\n" (etc... about 900 of them)
why am I unable to replace them
^ then it's option #2
What does your code look like
I'm giving it about 80% chance that you're not assigning the replaced value back to the variable
string fileData = File.ReadAllText(Application.persistentDataPath + "/file.csv");
Debug.Log(fileData.Replace("\n", @"\n"));
while (fileData.Contains("\n\n"))
{
fileData = fileData.Replace("\n\n","");
}
huh, not that
So what's happening?
Works for me: https://dotnetfiddle.net/VTRYX6
the string isn't getting the new lines removed for some reason
i was thinking it is the characters' representaion
now i know it is something very little and stupid
ill rewrite the code
string fileData = File.ReadAllText(Application.persistentDataPath + "/file.csv").Replace("\\n", "").Replace("\\r", "");
Show what the debug log prints (and what it prints after that while loop)
yep... it was a stupid thing from me...
It's also a bit strange to replace newlines in a CSV file, are you sure it's what you need to do?
i only update the value of the file if there's a line that's not \n\n
thank you all
i can't do that because that would make all the lines one line
thank you @mellow sigil and @quartz folio
which makes Nitku's question valid but you kinda answered that
I didn't even see it 😂
ahh, yeah lol
he was wondering why the removal of the new lines from a csv when that's the denotation of a new record
If you're under a canvas already then it's the canvas which performs sorting, so to do selective sorting below that you need subcanvases
You can also use a CanvasGroup to hide part of a hierarchy or stop it being interactable
I am instantiating hit effect vfx at the point of bullet collision on enemy but it is instantiating wierdly at the back of the enemy
Thanks but my question is about specifically scripts not other assets like textures, models, etc.
Categorize scripts in folders and namespaces. I usually use the combination of them.
I mean there are namespaces and folders like UI/featureA, Core/featureA, data/featureA and also FeatureB/UI, FeatureB/core
Environment.NewLine
If it helps you
Can someone help me out with the builtin buttons? I have no idea how to get them to run the function i want them to, or to do anything at all
you use events (subscriber pattern) using a custom implementation, or use built in functions like OnMouseDown() which also use events
your scene needs an Event System gameobject (under UI) to function properly if you use this route
usually if you add a canvas the event system also gets added
kk
I still only get the options for MonoScript -> string name
hmm
Or will onmouseup work now with the event system
it should
Oki
that sort of functionality should work out of the box with minimal setup, to call whatever code you need to call
Im testing hold on
the docs on these functions are useful as well
o right
shit you need a collider too
my bad lol
hmm
Just clicks the thing behind the button
Vector2 size = new Vector2(colliderSize.x, 0.001f);
RaycastHit2D[] results = Physics2D.BoxCastAll(start, size, 0, Vector2.down, Vector2.Distance(start, end), layermask);
with this 2 line of codes, it mean I use the box to find object by drag it down, right?
and with size.y there shouldn't be hit.point that is higher than start.y more than 0.001f, right?
red box is area that this boxcast go from start to end
The axis in the image is y=0.01520102
when I move out of the wall it work correctly
anyone know what's the problem?
The not canvas ones work
really? weird
whats the sort order of the canvas and the objects behind it?
why hit.point is on the opposite side of direction?
tho i wonder if the sort order does anything beyond impact rendering, I'm not actually sure here
usually you jsut need to offset it by atleast 1
Yeah the canvas ia above
right, okay hmm
I could try having an object that follows the cursor scaled to the canvas and detect a click
But that seems wrong
Maybe it is working but im not detecting it right
Inheritance problem perhaps
Nope
Odd
Ill keep trying
okay so I:
- added an empty scene
- added the button
- setup the OnClick in the button component to call the code I want from a gameobject in the scene with the script and code I want to call being set in the event (see screenshot)
and the event calls as long as the event system is in the scene
Ok let me try and copy this exactly
the code I wrote to be called is v simple too, but realistically you could call anything
ahh yeah, the script has to be on an object in the scene to be accessible
otherwise theres no reference afaik
I shoulda included it as a step to set up this object, my bad
Thanks
Is it because its an override void?
For me
Still not working
Im probably missing something stupid
public static event EventHandler OnAnyCut;
new public static void ResetStaticData() {
OnAnyCut = null;
}
Someone can explain the goal of reset a static event variable ?
Ah my bad - I use namespaces for features that can exist independent of others, for example a spell system doesnt need to know about the AI system, which doesnt need to know about the game settings, those 3 might be in different namespaces, organizing the scripts related to that spell system I might have a "System" folder for the namespace code as a base class and data class (ScriptableObject, JSON file, etc) and then a "Gameplay" folder that uses those base classes and data structure, for example:
//Might exist in: Assets/Systems/Scripts/Spells (with a "spells" assembly defintion file that uses a "Project.Magic" namespace)
namespace Project.Magic
{
public class Spell {} //base class for spell logic
public class SpellData : ScriptableObject {} //base class for data related to a spell, some Editor script could make it easier to customize this
}
//Might exist in: Assets/Gameplay/Scripts/Spells (no defition file, no namespace, instead it uses other namespaces)
using Project.Magic;
public class Fireball : Spell
{
public ProjectileSpellData data;
}
This is just how I would personally organize my code cause I find it easier using a "feature folder" to organize all assets of a project, including scripts, using both namespaces and a folder structure for your scripts is fine, there isnt really a "one size fits all" approach as the use-cases may be different and depend on different factors, though unless your organizing your assets by type or feature, where your scripts exist should be whatever is the most organized for you, unless your using assembly definition files as either auto-namespaces or to isolate code or optimize compile times, if I understand your concern correctly, hopefully that helps
I think im missing more stuff on the canvas
Yes i was
Its working now
Thanks guys 🙏
Bro i hate how gameobject.find cant find inactive objects
One of the many reasons why using Find at all is a bad idea
Can anybody help me regarding procedural dungeon generation (in 2D)? Am looking towards a dungeon generation like in Enter the Gungeon or similar games, which is generating using premade rooms of different sizes and premade hallways, and tilemaps. I was searching for a tutorial which covers this type of dungeon generation, but didn't find any covering this specific way, if you know a tutorial that covers this type of dungeon generation then I would be very happy to know. If you don't know any resources that could help me make a dungeon generator, I would appreciate a tutorial or tutorials on coding with tilemap itself, so I could maybe make my own dungeon generator.
Learn how to procedurally generate a 2D dungeon in Unity using Random Walk and Binary Space Partitioning algorithms! In this tutorial we will use unity Tilemaps to create single and multi room dungeons connected by corridors using Corridors First and Rooms first approaches.
Resources
https://github.com/SunnyValleyStudio/Unity_2D_Proecdural_Dun...
I saw this tutorial, but according to what I saw it is using also random room generation, while I want to place premade rooms and hallways. Still thanks, if I won't find anything then I will use this tutorial.
Is it a good idea to keep collectionchecks as always true for objectpool?
I was reading the documentation and it says that it only runs in the editor
GameObject zombieController = sender as GameObject;
RemoveGameobjectInList(zombieController);
IS THE SAME AS
ZombieController zombieController = sender as ZombieController;
RemoveGameobjectInList(zombieController.gameObject);
OR NOT ?
Not the same no, sender is a different type in each
I mean for what i do i can do with both ?
Is there a reason why Input.GetKeyDown is not always registering the input for me? I have an if statement in Update and it doesn't always register the fact the I press E
Like, I sometimes need to press the key multiple times (the amount of presses is random) for it to notice that. Sometimes it works on the first try, sometimes on 10th
show code
private bool Epressed;
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Epressed = true;
}
else
{
Epressed = false;
}
}
This is literally it. I use Epressed bool later in an if statements in OnTriggerStay, but I checked with Debug.Log that the OnTriggerStay works correctly
Put a debug.log inside the if statement to confirm that it's this part that's not working
ah, nevermind. OnTriggerStay runs during the FixedUpdate phase. This can set the flag to false before OnTriggerStay gets to run.
Set the flag to false in the OnTriggerStay code, not here
I'll try that
Still doesn't work. I've put it in OnTriggerStay and the Debug.Log doesn't always activate
if (Input.GetKeyDown(KeyCode.E))
{
Epressed = true;
Debug.Log("E pressed!");
}
else
{
Epressed = false;
}
So you didn't remove the part that sets the flag to false
I'll check it without that part
Still doesn't always work. I need few presses sometimes to activate that bool
I mean, in Debug tag I can see that the bool doesn't activate when I stay on trigger and press E
Show what you have now, including the ontriggerstay
I think that it's too long. I have a shitton of if statements. Could that interfere with the input?
no
I made a program that if the player touches a collider (which is set on tirgger), it respawns the player and adds money through another script i made. Whenever the player touches the collider, nothing seems to be happening, does anyone know why? here is the script:
show the relevant parts
using UnityEngine;
public class FinishLine : MonoBehaviour
{
public int moneyToAdd = 10;
public Transform respawnPoint;
// Called when the player enters the collider
void OnTriggerEnter2D(Collider2D other)
{
// Check if the other collider belongs to the player
if (other.CompareTag("Player"))
{
// Get the player's money manager component
MoneyManager moneyManager = other.GetComponent<MoneyManager>();
// Add money to the player's current amount
if (moneyManager != null)
{
moneyManager.ModifyMoney(moneyToAdd);
}
// Respawn the player at the respawn point
other.transform.position = respawnPoint.position;
}
}
}
MoneyManager is the other script i made
for some reason the player wont respawn or add money, i even checked using a debug.log and it doesnt even do that
Why is there no output being sent when the player touches the collider (which is set on trigger)?
Does your player have the tag Player
yes it does
do both objects have colliders and does your player have a rigid body?
Yes both objects have a collider, but my player doesnt have a rigid body. That must be the problem
Lemme see if that fixes it
private void OnTriggerStay2D(Collider2D collision)
{
if (Input.GetKeyDown(KeyCode.E))
{
Epressed = true;
Debug.Log("E pressed!");
}
if (_shootScript.guns == Shoot.Guns.SMG && Epressed)
{
//Do somethingg
}
}
The last if statement is repeated few times with different requirements from _shootScript.guns
Only 2 other if's need the Epressed
Ok you moved everything to the OnTriggerStay method. You were only supposed to move the part that sets the flag to false
oh
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Epressed = true;
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if (Epressed)
{
// do whatever
Epressed = false;
}
}
Yo it works, thanks so much
Thanks man, it works now 👍
Does the Multiple Selector support pseudoclasses?
Looking for assistance here if anyone knows what i need
Like this guy does
https://medium.com/teamarimac/how-to-develop-a-complete-leader-board-for-a-unity-game-using-firebase-facebook-sign-in-google-d865f577b303
use an enum if you know how many factions there will be
otherwise just use a integer to store the faction id
How that work.
I don't see how you can do this with int.
e.g team 1 is 1
shouldnt be that hard to understand lol
just means you don't hard code the amount of factions as an enum
you know your game better than me so you'll know how many factions is possible
Yeah so enum is better.
And if you want some faction to be friendly together you need to store it
With dynamic int that look strange to do
well at that point i'd make a factions manager and store faction data on that which can then have all that custom stuff in it
you shouldnt really touch the team stuff in code outside the manager so using a int would be fine (not hardcoding stuff)
You'd actually have a faction class to store the faction data
public class Faction
{
public int FactionId;
public List<Faction> FriendlyFactions = new List<Faction>();
//Other faction dependent stuff
}
isn't this the burst compiler? can I just delete the package for it or something?
or gitignore? or is that gonna cause issues
in case it's not apparent, I'm not using the burst compiler
You shouldn't commit library files to git. Either you don't have a gitignore file or there's something wrong with it
^
I mean, my gitignore is a standard unity ignore file, and it's supposedly already ignoring the library folder
not sure what's wrong with it
Is it in the pong-clone directory?
so no
it needs to be in the Unity project directory (pong-clone)
usually the git root directory is also there
yeah that worked, obviously
I've been using bitbucket for a long time and just recently switched to github so I guess I screwed up the repo somehow
thanks @mellow sigil
{
RayCasting();
if (isGrounded)
{
rb.constraints = RigidbodyConstraints.FreezeAll;
cameraShake();
Debug.Log("Frozen");
if (!GameManager.instance.isTrapped)
{
StartCoroutine(ResetCage());
Debug.Log("Reset");
}
}
}
IEnumerator ResetCage()
{
theCage.transform.position = Vector3.MoveTowards(theCage.transform.position, cageOriginalPosition, Time.deltaTime * 2);
yield return null;
}```
I may be stupid but anyone know why the IEnumerator isnt moving theCage's position
wait
loop
i am just stupid
When I multiply a quaternion by a quaternion am I rotating the initial quat by the 2nd similar to how it rotates a vector?
Tyvm for the resource
So I have a list of blockPositions I then randomly pick one and add it new a new list newRandomPositions I can see that my blockPositions list has 6 items in it but after debugging it seems to only add 3 to the newRandomPositions list.
Any thoughts on what I might be doing wrong?
List<Vector3> blockPositions = new List<Vector3>();
blockPositions.Add(block_Slot3_level2);
blockPositions.Add(block_Slot6_level2);
blockPositions.Add(block_Slot5_levle2);
blockPositions.Add(block_Slot4_level2);
blockPositions.Add(block_Slot1_level2);
blockPositions.Add(block_Slot2_level2);
List<Vector3> newRandomPositions = new List<Vector3>();
for (int i = 0; i < blockPositions.Count; i++)
{
int ran = (Random.Range(0, blockPositions.Count-1));
newRandomPositions.Add(blockPositions[ran]);
blockPositions.RemoveAt(i);
}
when i load a new scene asynchronously the progress goes to 0.9 and then it stops for a long time . how can i reduce that loading time?
i saw a brackey's video about loading scene and he said the first 0.9 is for loading gameobject and other 0.1 if deleting previous and activating new objects so is that causing this time and if yes then how can i improve the time?
i am using this code
public void LoadScene(string sceneName)
{
StartCoroutine(LoadSceneAsync(sceneName));
}
IEnumerator LoadSceneAsync(string sceneName)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneName);
Loadingscreen.SetActive(true);
while (!operation.isDone)
{
float progressValue = Mathf.Clamp01(operation.progress/0.9f);
LoadingBar.fillAmount = progressValue;
yield return null;
}
}
probably because you're modifying the list while iterating through it. In your case I guess you can just shuffle it instead of creating a new list?
// IListExtensions.cs
public static class IListExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count - 1;
while (n > 0)
{
int k = Random.Range(0, n);
T value = list[k];
list[k] = list[n];
list[n] = value;
--n;
}
}
}
Thanks @daring nymph that's a really smart approach. Is there a way to use this without making my class static?
I posted an extension method (notice the this keyword), and regardless of whether you want it to be an extension method or just a regular method it doesnt have to be in the same file as your code that is using it. the easiest thing you can do to just make a separate file with a static Util class and put that Shuffle method in there to make it accessible anywhere
or if you keep it as an extension method, then you can just do blockPositions.Shuffle()
edited
Wow that's really cool thanks so much @daring nymph you solution works perfectly and is much cleaner than my solution!
Even better I can already see how this Utils class will be useful going forward. I haven't really came across extension methods before but will do a little reading into them.
My current project has taught me a lot of new concepts - Inheritance, state machines, singletons etc so I'm always excited to see new techniques.
nice! keep in mind that it shuffles in place, so if you want a shuffled version of your original list without modifying the original be sure to copy it first, i.e var shuffled = blockPositions.ToList().Shuffle()
Cool! For my current needs it will probably be ok rearrange the actual list but I've added your note as comment to my class for the future as I'm sure it'll crop up at some point 🙂
Someone said I should use delegates if I wanted to pick a random function out of like 20. How would I do this?
Like I know how to define a delegate function and that you can use them in an array but like
How does that help pick a random function
If you get as far as having the delegates in an array then picking a random one from there is the easy part
I guess my question should've been how the hell do I assign functions to a delegate?
That sounds stupid but if I have multiple voids how can I use a single list of a delegate to run those?
I don't know what you mean by "a single list of a delegate"
Wait hold on
So I just saw an example of someone making a delegate void and then doing delegatevoid(function)
Is that how they work lol?
An array of a delegate even
Goddamnit
This is so confusing
You can make an array of delegates just like any other types
How can I use a delegate to pick a random function and run it though
That's where I'm stuck
hi ,
is it possible to clear the entires of an enum and replace it with a newer ones via script/editor script?
You speak of "a delegate" so I think that's what's tripping you
If you want to pick one from 20 functions you make 20 different delegates and put those in an array
each delegate runs one of the 20 functions
Ohhhhh
I completely misunderstood
I was thinking people somehow stuffed multiple functions into one delegate
Ok just to be certain though I don't have access to my PC currently
How would you make an array of delegates
Oh wait nevermind it seems to be like any normal thing
Alrighty then
instantiating a prefab and then modifying it's rigidbody after the fact, but for some reason I'm getting "the variable rb has not been assigned" anyone know why?
not sure how I'm supposed to assign a variable I'm creating at runtime
just realized I made a float an int but ignore that
I have the rb field and use GetComponent in awake like you would normally
If you're instantiating a prefab you can assign the variable in it directly. If it's a public variable or has [SerializeField] added then you should be able to see it in the inspector and modify it. Simply drag Rigidbody component or GameObject the Rigidbody is attached to, then drop it onto the rb variable in the inspector.
Hey guys I'm really new and using visual script. On the tutorial in unity the guy types the code and suggestions pop up such as vector3 ect. Does anyone know how to enable that
I'm adding a component that doesn't exist in the hierarchy until I instantiate it, so there's no field to drag a Rigidbody into. The rigidbody is already part of the prefab and I grab it with GetComponent, I hope that makes sense
there's no rb = GetComponent<Rigidbody>() in your screenshot though
well I screenshotted the method that the staketrace gave as giving an error, but I do have a getcomponent call in awake
Any ideas on creating shotgun shoot script on 2D. Struggling with the randomness on the rays
[RequireComponent(typeof(Rigidbody2D), typeof(CircleCollider2D))]
public class DefaultPuck : MonoBehaviour, IPuck
{
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
public void Punch()
{
float direction = Random.Range(0, 1);
if (direction >= 0.5)
{
rb.velocity += GameManager.instance.puckSpeed;
}
else rb.velocity += Vector2.left * GameManager.instance.puckSpeed;
}
so you're adding DefaultPuck dynamically at runtime?
yes
does that avoid an Awake call or something? that would explain the error, although not make sense lol
yeah that must be it, according to unity docs:
Awake is called either when an active GameObject that contains the script is initialized when a Scene loads, or when a previously inactive GameObject is set to active, or after a GameObject created with Object.Instantiate is initialized.
wow. Okay.
thank you, that's somewhat frustrating but not as bad as I thought it was @daring nymph
yeah well not a big deal is it, you can just move that GetComponent into a new Init method and then just AddComponent<DefaultPuck>().Init()
good idea. Thanks for the help
I keep getting these in editor whenever I open any prefab, regardless of what's in it. Any thoughts?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
so you didn't read the bot message did you
you're flooding this entire chat no one will read this
put them in links
I had a quick google sadly not too much comes up for that error. One suggestion was that it could be related to async or tasks?
Hey, wondering if I have this right, I want to apply 2 rotations simultaneously, so I have to negate the first rotation when applying the second right?
Quaternion.LookRotation(smoothedMoveInput) * (Quaternion.AngleAxis(angle, axis) * Quaternion.Inverse(Quaternion.LookRotation(smoothedMoveInput))
yeah I so that too, but no, I avoid async in my code
why would you negate it, won't it be just Quaternion.AngleAxis(angle, axis) in the end ? 
hey,
is it possible to make a slow AsyncOperation ?
why
trying to design a loading screen based on heavy asyncOperation , so I need one of a few to test it.
can't you use a delay in a while loop coroutine ?
yield return new WaitForSeconds(2f);
hmm , I'll try that , I have no idea what is concidered as a AsyncOp and what is not
private AsyncOperation asyncLoad;
void Start()
{
StartCoroutine(LoadSceneAsync());
}
IEnumerator LoadSceneAsync()
{
asyncLoad = SceneManager.LoadSceneAsync("MainScene");
asyncLoad.allowSceneActivation = false;
while (!asyncLoad.isDone)
{
Debug.Log("LOADING...");
if (asyncLoad.progress >= 0.9f)
{
yield return new WaitForSeconds(3.4f);
Debug.Log("Done");
asyncLoad.allowSceneActivation = true;
}
yield return null;
}
}```
mayb
that is a nice example , thank you so much ❤️
is it better to have decoupled code or performant code?
cause I'm making some systems within my game in which they both have shared functionality
I could have it so that these 2 systems communicate with each other and share functionality, but that will make it harder when I introduce assembly definitions later down the line
Still need help here if anyone knows what I need to do
just received this warning, should I be concerned? (I haven't deleted any scripts or anything so I don't know why this appearing)
hey,
int A =2 ;
int B 20;
float result = Mathf.Round((float)A / (float)B) * 100;
why result == 0 ??
that was suppose to be 10
ohh
Thanks ❤️
np
You can have both. If it's really performance-critical part, I don't think sacrificing good code is gonna help much. There are probably better ways to optimize the systems. But we don't know the details of your case, so hard to suggest anything.
I would say separating your logic into reusable classes as often as possible is always good, even better if you can find ways to make that class generic so its not specifically built around the dependency of one other specific system - for example, a save system could be generic enough to save any kind of data, then your settings, level manager, player progression like stats and unlockables etc can all use it without needing their own specific save/load class - for context though, what are the 2 systems in question? And how do you intend to use your assembly definitions where just a namespace may not be be enough?
Hey!! Anyone know how I would go about using Render Textures to generate a texture where this flower image is overlayed over another?
You've asked several times and didn't get a reply. That probably means that no one understands what you're asking.
At least I don't. Is the gray thing the "flower image"? Generate what texture? What exactly are you trying to do?
What would be more efficient? OnTriggerEnter/Exit, or using Physics.Overlap every fixedupdate?
Sorry I am probably explaining poorly. Right now I'm trying to "merge" 2 texture 2Ds so that a background is visible behind the cut out of the flower. This merged texture would become its own texture2D. The gray part is the alpha.
The former.
So, if I understand correctly, there's some background texture and the one that you shared above. And you want to render the one that you shared above on top of the background, but the gray area need to be transparent?
I want the one I shared to be rendered as the foreground to a background texture
Ok, so what is the problem?
At the moment my main problem is just getting the scaling right, pretty sure I'm setting something wrong with the width and height somewhere along the line
Lemme pull up my current code it'll probably help lol
int randomIndex = UnityEngine.Random.Range(0, imagePaths.Length);
string randomImagePath = imagePaths[randomIndex];
byte[] bytes = File.ReadAllBytes(randomImagePath)
;
Texture2D flower = flowerImages[UnityEngine.Random.Range(0, flowerImages.Length)];
Texture2D texture = new Texture2D(flower.width, flower.height);
texture.LoadImage(bytes);
texture.Apply();
AddWatermark(texture, flower);
public Texture2D AddWatermark(Texture2D background, Texture2D watermark)
{
int startX = 0;
int startY = background.height - watermark.height;
for (int x = startX; x < watermark.width; x++)
{
for (int y = startY; y < watermark.height; y++)
{
Color bgColor = background.GetPixel(x, y);
Color wmColor = watermark.GetPixel(x - startX, y - startY);
Color final_color = Color.Lerp(bgColor, wmColor, wmColor.a / 1.0f);
background.SetPixel(x, y, final_color);
}
}
background.Apply();
Rect rec = new Rect(0, 0, background.width, background.height);
img.sprite = Sprite.Create(background, rec, new Vector2(0, 0), 1f);
Application.Quit();
return background;
}
If possible I want the output texture to be of the same width and height as the flower texture, however, the outputs rn are pretty wonky
Example of current output
If you want to have more control over the width/height and offset, why not just have 2 sprites with your textures set up(so that you can configure it in the scene view) and render the result to a render texture.
So sorry I'm a bit of a moron when it comes to render textures how would I exactly set that up so it can then be exported as a png
Anyone know how to force Unity to run at max possible FPS on android devices?
On my android phone, it's defaulting to 30FPS when it supports 120FPS.
Something like this.
https://forum.unity.com/threads/save-rendertexture-or-texture2d-as-image-file-utility.1325130/
Might need to replace some code. I think the texture encoding methods were moved here:
https://docs.unity3d.com/ScriptReference/ImageConversion.EncodeToPNG.html
Just set the target frame rate to 120
It's a pretty bad idea though
