How set background of activity via Unity3d

124 Views Asked by At

I made an Android plugin for Unity3d that changes the background on the launch screen, now the background is registered using code:

 <style name="SplashScreen" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        **<item name="android:windowBackground">@drawable/background_splashscreen</item>**
 </style>

How can you change it using code in Unity?(Apparently you need to use native code)

1

There are 1 best solutions below

1
TheGhost On

To set the background of an Activity via Unity3D, you can make use of the "UnityPlayerActivity" class provided by Unity. Here are the steps to achieve this:

  1. In your Unity project, navigate to the "Assets/Plugins/Android" folder. If the folder doesn't exist, create it.

  2. Create a new Java class file within the "Android" folder and name it something like "CustomUnityPlayerActivity".

  3. Open the "CustomUnityPlayerActivity" file and extend it from "com.unity3d.player.UnityPlayerActivity":

import com.unity3d.player.UnityPlayerActivity;

public class CustomUnityPlayerActivity extends UnityPlayerActivity {

}
  1. Add the required import statements at the top of the file:
import android.graphics.Color;
import android.view.View;
  1. Override the "onCreate()" method within the "CustomUnityPlayerActivity" class:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the background color of the activity
    getWindow().getDecorView().setBackgroundColor(Color.RED);
}
  1. Save the Java file.

  2. Export your Unity project for Android as an APK.

  3. Open your Android project in Android Studio.

  4. In the "build.gradle" file of your Android project, add the following line to the "dependencies" section:

implementation project(':unityLibrary')

Make sure to replace "unityLibrary" with the name of your Unity library module.

  1. In the AndroidManifest.xml file of your Android project, locate the <activity> tag that represents the UnityPlayerActivity and change its name to reference your custom activity, like this:
<activity android:name=".CustomUnityPlayerActivity"
          android:label="@string/app_name"
          android:screenOrientation="landscape"
          android:launchMode="singleTask"
          android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
          android:configChanges="keyboardHidden|orientation|screenSize">
  1. Build and run your Android project on your device or emulator.

With these steps, you should now have a custom UnityPlayerActivity that sets the background color of the Activity to red. You can modify the setBackgroundColor method with any color or background resource that you desire.