Ejemplo n.º 1
0
        public static byte[] myLuaLoader(ref string filepath)
        {
            byte[] bytes   = null;
            string luaPath = "";
            string strs    = "";

            try
            {
                if (!filepath.StartsWith(CLPathCfg.self.basePath))
                {
                    //说明是通过require进来的
                    filepath = filepath.Replace(".", "/");
                    filepath = PStr.b().a(CLPathCfg.self.basePath).a("/upgradeRes/priority/lua/").a(filepath).a(".lua").e();
                }

#if UNITY_EDITOR
                if (CLCfgBase.self.isEditMode)
                {
                    filepath = filepath.Replace("/upgradeRes/", "/upgradeRes4Dev/");
                    luaPath  = PStr.b().a(Application.dataPath).a("/").a(filepath).e();
                    bytes    = MapEx.getBytes(FileBytesCacheMap, luaPath);
                    if (bytes != null)
                    {
                        filepath = luaPath;
                        return(bytes);
                    }
                    if (File.Exists(luaPath))
                    {
                        strs     = FileEx.getTextFromCache(luaPath);
                        bytes    = System.Text.Encoding.UTF8.GetBytes(strs);
                        filepath = luaPath;
                        return(bytes);
                    }
                }
#endif

#if UNITY_WEBGL
                bytes = MapEx.getBytes(FileBytesCacheMap, filepath);
                if (bytes != null)
                {
                    return(bytes);
                }
                else
                {
                    bytes = FileEx.readNewAllBytes(filepath);
                    bytes = deCodeLua(bytes);
                    FileBytesCacheMap[filepath] = bytes;
                    return(bytes);
                }
#else
                //=======================================================
                //1.first  load from CLPathCfg.persistentDataPath;
                luaPath = PStr.b().a(CLPathCfg.persistentDataPath).a("/").a(filepath).e();
                bytes   = MapEx.getBytes(FileBytesCacheMap, luaPath);
                if (bytes != null)
                {
                    filepath = luaPath;
                    return(bytes);
                }
                if (File.Exists(luaPath))
                {
                    bytes = FileEx.getBytesFromCache(luaPath);
                    if (bytes != null)
                    {
//					bytes = System.Text.Encoding.UTF8.GetBytes(strs);
                        bytes = deCodeLua(bytes);
                        FileBytesCacheMap [luaPath] = bytes;
                        filepath = luaPath;
                        return(bytes);
                    }
                }
                //=======================================================
                //2.second load from  Application.streamingAssetsPath;
                luaPath = PStr.b().a(Application.streamingAssetsPath).a("/").a(filepath).e();
                bytes   = MapEx.getBytes(FileBytesCacheMap, luaPath);
                if (bytes != null)
                {
                    filepath = luaPath;
                    return(bytes);
                }

                bytes = FileEx.getBytesFromCache(luaPath);
                if (bytes != null)
                {
//				bytes = System.Text.Encoding.UTF8.GetBytes(strs);
                    bytes = deCodeLua(bytes);
                    FileBytesCacheMap [luaPath] = bytes;
                    filepath = luaPath;
                    return(bytes);
                }

                //=======================================================
                //3.third load from Resources.Load ();
                luaPath = filepath;
                bytes   = MapEx.getBytes(FileBytesCacheMap, luaPath);
                if (bytes != null)
                {
                    filepath = luaPath;
                    return(bytes);
                }

                TextAsset text = Resources.Load <TextAsset>(filepath);
                if (text != null)
                {
                    bytes = text.bytes;// System.Text.Encoding.UTF8.GetBytes(text.text);
                    if (bytes != null)
                    {
                        bytes = deCodeLua(bytes);
                        FileBytesCacheMap[luaPath] = bytes;
                        filepath = luaPath;
                        return(bytes);
                    }
                }
                //==========================
                return(bytes);
#endif
            }
            catch (System.Exception e)
            {
                Debug.LogError(luaPath + ":" + e);
                return(null);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// initializes resources (mapDistanceSquaredFromWater, mapDistanceSquaredFromLocations, mapMultipliers) and smoothes small height map
        /// </summary>
        public static void InitImprovedWorldTerrain(ContentReader contentReader)
        {
            if (!init)
            {
                #if CREATE_PERSISTENT_LOCATION_RANGE_MAPS
                {
                    int width  = WoodsFile.mapWidthValue;
                    int height = WoodsFile.mapHeightValue;

                    mapLocationRangeX = new byte[width * height];
                    mapLocationRangeY = new byte[width * height];

                    //int y = 204;
                    //int x = 718;
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            //MapPixelData MapData = TerrainHelper.GetMapPixelData(contentReader, x, y);
                            //if (MapData.hasLocation)
                            //{
                            //    int locationRangeX = (int)MapData.locationRect.xMax - (int)MapData.locationRect.xMin;
                            //    int locationRangeY = (int)MapData.locationRect.yMax - (int)MapData.locationRect.yMin;
                            //}

                            ContentReader.MapSummary mapSummary;
                            int  regionIndex = -1, mapIndex = -1;
                            bool hasLocation = contentReader.HasLocation(x, y, out mapSummary);
                            if (hasLocation)
                            {
                                regionIndex = mapSummary.RegionIndex;
                                mapIndex    = mapSummary.MapIndex;
                                DFLocation location       = contentReader.MapFileReader.GetLocation(regionIndex, mapIndex);
                                byte       locationRangeX = location.Exterior.ExteriorData.Width;
                                byte       locationRangeY = location.Exterior.ExteriorData.Height;

                                mapLocationRangeX[y * width + x] = locationRangeX;
                                mapLocationRangeY[y * width + x] = locationRangeY;
                            }
                        }
                    }

                    // save to files
                    FileStream ostream;
                    ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathMapLocationRangeX), FileMode.Create, FileAccess.Write);
                    BinaryWriter writerMapLocationRangeX = new BinaryWriter(ostream, Encoding.UTF8);
                    writerMapLocationRangeX.Write(mapLocationRangeX, 0, width * height);
                    writerMapLocationRangeX.Close();
                    ostream.Close();

                    ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathMapLocationRangeY), FileMode.Create, FileAccess.Write);
                    BinaryWriter writerMapLocationRangeY = new BinaryWriter(ostream, Encoding.UTF8);
                    writerMapLocationRangeY.Write(mapLocationRangeY, 0, width * height);
                    writerMapLocationRangeY.Close();
                    ostream.Close();
                }
                #else
                {
                    int width  = WoodsFile.mapWidthValue;
                    int height = WoodsFile.mapHeightValue;

                    mapLocationRangeX = new byte[width * height];
                    mapLocationRangeY = new byte[width * height];

                    MemoryStream istream;
                    TextAsset    assetMapLocationRangeX = Resources.Load <TextAsset>(filenameMapLocationRangeX);
                    if (assetMapLocationRangeX != null)
                    {
                        istream = new MemoryStream(assetMapLocationRangeX.bytes);
                        BinaryReader readerMapLocationRangeX = new BinaryReader(istream, Encoding.UTF8);
                        readerMapLocationRangeX.Read(mapLocationRangeX, 0, width * height);
                        readerMapLocationRangeX.Close();
                        istream.Close();
                    }

                    TextAsset assetMapLocationRangeY = Resources.Load <TextAsset>(filenameMapLocationRangeY);
                    if (assetMapLocationRangeY)
                    {
                        istream = new MemoryStream(assetMapLocationRangeY.bytes);
                        BinaryReader readerMapLocationRangeY = new BinaryReader(istream, Encoding.UTF8);
                        readerMapLocationRangeY.Read(mapLocationRangeY, 0, width * height);
                        readerMapLocationRangeY.Close();
                        istream.Close();
                    }

                    //FileStream istream;
                    //istream = new FileStream(filepathMapLocationRangeX, FileMode.Open, FileAccess.Read);
                    //BinaryReader readerMapLocationRangeX = new BinaryReader(istream, Encoding.UTF8);
                    //readerMapLocationRangeX.Read(mapLocationRangeX, 0, width * height);
                    //readerMapLocationRangeX.Close();
                    //istream.Close();

                    //istream = new FileStream(filepathMapLocationRangeY, FileMode.Open, FileAccess.Read);
                    //BinaryReader readerMapLocationRangeY = new BinaryReader(istream, Encoding.UTF8);
                    //readerMapLocationRangeY.Read(mapLocationRangeY, 0, width * height);
                    //readerMapLocationRangeY.Close();
                    //istream.Close();
                }
                #endif

                if (mapDistanceSquaredFromWater == null)
                {
                    byte[] heightMapArray = contentReader.WoodsFileReader.Buffer.Clone() as byte[];
                    int    width          = WoodsFile.mapWidthValue;
                    int    height         = WoodsFile.mapHeightValue;
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            if (heightMapArray[y * width + x] <= 2)
                            {
                                heightMapArray[y * width + x] = 1;
                            }
                            else
                            {
                                heightMapArray[y * width + x] = 0;
                            }
                        }
                    }
                    //now set image borders to "water" (this is a workaround to prevent mountains to become too high in north-east and south-east edge of map)
                    for (int y = 0; y < height; y++)
                    {
                        heightMapArray[y * width + 0]         = 1;
                        heightMapArray[y * width + width - 1] = 1;
                    }
                    for (int x = 0; x < width; x++)
                    {
                        heightMapArray[0 * width + x]            = 1;
                        heightMapArray[(height - 1) * width + x] = 1;
                    }

                    mapDistanceSquaredFromWater = imageDistanceTransform(heightMapArray, width, height, 1);

                    heightMapArray = null;
                }

                if (mapDistanceSquaredFromLocations == null)
                {
                    int width  = WoodsFile.mapWidthValue;
                    int height = WoodsFile.mapHeightValue;
                    mapLocations = new byte[width * height];

                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            ContentReader.MapSummary summary;
                            if (contentReader.HasLocation(x + 1, y + 1, out summary))
                            {
                                mapLocations[y * width + x] = 1;
                            }
                            else
                            {
                                mapLocations[y * width + x] = 0;
                            }
                        }
                    }
                    mapDistanceSquaredFromLocations = imageDistanceTransform(mapLocations, width, height, 1);
                }

                if (mapMultipliers == null)
                {
                    int width  = WoodsFile.mapWidthValue;
                    int height = WoodsFile.mapHeightValue;
                    mapMultipliers = new float[width * height];

                    // compute the multiplier and store it in mapMultipliers
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            float distanceFromWater    = (float)Math.Sqrt(mapDistanceSquaredFromWater[y * WoodsFile.mapWidthValue + x]);
                            float distanceFromLocation = (float)Math.Sqrt(mapDistanceSquaredFromLocations[y * WoodsFile.mapWidthValue + x]);
                            float multiplierLocation   = (distanceFromLocation * extraExaggerationFactorLocationDistance + 1.0f); // terrain distant from location gets extra exaggeration
                            if (distanceFromWater < minDistanceFromWaterForExtraExaggeration)                                     // except if it is near water
                            {
                                multiplierLocation = 1.0f;
                            }

                            // Seed random with terrain key
                            UnityEngine.Random.InitState(TerrainHelper.MakeTerrainKey(x, y));

                            float additionalHeightBasedOnClimate = GetAdditionalHeightBasedOnClimate(x, y);
                            float additionalHeightApplied        = UnityEngine.Random.Range(-additionalHeightBasedOnClimate * 0.5f, additionalHeightBasedOnClimate);
                            mapMultipliers[y * width + x] = (Math.Min(maxHeightsExaggerationMultiplier, additionalHeightApplied + /*multiplierLocation **/ Math.Max(1.0f, distanceFromWater * exaggerationFactorWaterDistance)));
                        }
                    }

                    // multipliedMap gets smoothed
                    float[] newmapMultipliers = mapMultipliers.Clone() as float[];
                    float[,] weights = { { 0.0625f, 0.125f, 0.0625f }, { 0.125f, 0.25f, 0.125f }, { 0.0625f, 0.125f, 0.0625f } };
                    for (int y = 1; y < height - 1; y++)
                    {
                        for (int x = 1; x < width - 1; x++)
                        {
                            if (mapDistanceSquaredFromLocations[y * width + x] <= 2) // at and around locations ( <= 2 ... only map pixels in 8-connected neighborhood (distanceFromLocationMaps stores squared distances...))
                            {
                                newmapMultipliers[y * width + x] =
                                    weights[0, 0] * mapMultipliers[(y - 1) * width + (x - 1)] + weights[0, 1] * mapMultipliers[(y - 1) * width + (x)] + weights[0, 2] * mapMultipliers[(y - 1) * width + (x + 1)] +
                                    weights[1, 0] * mapMultipliers[(y - 0) * width + (x - 1)] + weights[1, 1] * mapMultipliers[(y - 0) * width + (x)] + weights[1, 2] * mapMultipliers[(y - 0) * width + (x + 1)] +
                                    weights[2, 0] * mapMultipliers[(y + 1) * width + (x - 1)] + weights[2, 1] * mapMultipliers[(y + 1) * width + (x)] + weights[2, 2] * mapMultipliers[(y + 1) * width + (x + 1)];
                            }
                        }
                    }
                    mapMultipliers = newmapMultipliers;

                    newmapMultipliers = null;
                    weights           = null;
                }

                //the height map gets smoothed as well
                {
                    int    width           = WoodsFile.mapWidthValue;
                    int    height          = WoodsFile.mapHeightValue;
                    byte[] heightMapBuffer = contentReader.WoodsFileReader.Buffer.Clone() as byte[];
                    int[,] intWeights = { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } };
                    for (int y = 1; y < height - 1; y++)
                    {
                        for (int x = 1; x < width - 1; x++)
                        {
                            if (mapDistanceSquaredFromWater[y * width + x] > 0) // check if squared distance from water is greater than zero -> if it is no water pixel
                            {
                                int value =
                                    intWeights[0, 0] * (int)heightMapBuffer[(y - 1) * width + (x - 1)] + intWeights[0, 1] * (int)heightMapBuffer[(y - 1) * width + (x)] + intWeights[0, 2] * (int)heightMapBuffer[(y - 1) * width + (x + 1)] +
                                    intWeights[1, 0] * (int)heightMapBuffer[(y - 0) * width + (x - 1)] + intWeights[1, 1] * (int)heightMapBuffer[(y - 0) * width + (x)] + intWeights[1, 2] * (int)heightMapBuffer[(y - 0) * width + (x + 1)] +
                                    intWeights[2, 0] * (int)heightMapBuffer[(y + 1) * width + (x - 1)] + intWeights[2, 1] * (int)heightMapBuffer[(y + 1) * width + (x)] + intWeights[2, 2] * (int)heightMapBuffer[(y + 1) * width + (x + 1)];

                                heightMapBuffer[y * width + x] = (byte)(value / 16);
                            }
                        }
                    }
                    contentReader.WoodsFileReader.Buffer = heightMapBuffer;

                    heightMapBuffer = null;
                    intWeights      = null;
                }

                // build tree coverage map
                if (mapTreeCoverage == null)
                {
                    int width  = WoodsFile.mapWidthValue;
                    int height = WoodsFile.mapHeightValue;
                    mapTreeCoverage = new byte[width * height];

                    #if !LOAD_TREE_COVERAGE_MAP
                    {
                        float startTreeCoverageAtElevation = ImprovedTerrainSampler.baseHeightScale * 2.0f; // ImprovedTerrainSampler.scaledBeachElevation;
                        float minTreeCoverageSaturated     = ImprovedTerrainSampler.baseHeightScale * 6.0f;
                        float maxTreeCoverageSaturated     = ImprovedTerrainSampler.baseHeightScale * 60.0f;
                        float endTreeCoverageAtElevation   = ImprovedTerrainSampler.baseHeightScale * 80.0f;
                        //float maxElevation = 0.0f;
                        for (int y = 0; y < height; y++)
                        {
                            for (int x = 0; x < width; x++)
                            {
                                int   readIndex = (height - 1 - y) * width + x;
                                float w         = 0.0f;

                                //float elevation = ((float)contentReader.WoodsFileReader.Buffer[(height - 1 - y) * width + x]) / 255.0f; // *mapMultipliers[index];
                                float elevation = ((float)contentReader.WoodsFileReader.Buffer[readIndex]) * mapMultipliers[readIndex];

                                //maxElevation = Math.Max(maxElevation, elevation);
                                if ((elevation > minTreeCoverageSaturated) && (elevation < maxTreeCoverageSaturated))
                                {
                                    w = 1.0f;
                                }
                                else if ((elevation >= startTreeCoverageAtElevation) && (elevation <= minTreeCoverageSaturated))
                                {
                                    w = (elevation - startTreeCoverageAtElevation) / (minTreeCoverageSaturated - startTreeCoverageAtElevation);
                                }
                                else if ((elevation >= maxTreeCoverageSaturated) && (elevation <= endTreeCoverageAtElevation))
                                {
                                    w = 1.0f - ((elevation - maxTreeCoverageSaturated) / (endTreeCoverageAtElevation - maxTreeCoverageSaturated));
                                }

                                //w = 0.65f * w + 0.35f * Math.Min(6.0f, (float)Math.Sqrt(mapDistanceSquaredFromLocations[y * width + x])) / 6.0f;

                                mapTreeCoverage[(y) * width + x] = Convert.ToByte(w * 255.0f);

                                //if (elevation>0.05f)
                                //    mapTreeCoverage[index] = Convert.ToByte(250); //w * 255.0f);
                                //else mapTreeCoverage[index] = Convert.ToByte(0);

                                //if (elevation >= startTreeCoverageAtElevation)
                                //{
                                //    mapTreeCoverage[(y) * width + x] = Convert.ToByte(255.0f);
                                //} else{
                                //    mapTreeCoverage[(y) * width + x] = Convert.ToByte(0.0f);
                                //}
                            }
                        }
                    }
                    #else
                    {
                        MemoryStream istream;
                        TextAsset    assetMapTreeCoverage = Resources.Load <TextAsset>(filenameTreeCoverageMap);
                        if (assetMapTreeCoverage)
                        {
                            istream = new MemoryStream(assetMapTreeCoverage.bytes);
                            BinaryReader readerMapTreeCoverage = new BinaryReader(istream, Encoding.UTF8);
                            readerMapTreeCoverage.Read(mapTreeCoverage, 0, width * height);
                            readerMapTreeCoverage.Close();
                            istream.Close();
                        }
                    }
                    #endif

                    #if CREATE_PERSISTENT_TREE_COVERAGE_MAP
                    {
                        FileStream   ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathOutTreeCoverageMap), FileMode.Create, FileAccess.Write);
                        BinaryWriter writerMapTreeCoverage = new BinaryWriter(ostream, Encoding.UTF8);
                        writerMapTreeCoverage.Write(mapTreeCoverage, 0, width * height);
                        writerMapTreeCoverage.Close();
                        ostream.Close();
                    }
                    #endif
                    //Debug.Log(string.Format("max elevation: {0}", maxElevation));
                }

                init = true;
            }
        }
Ejemplo n.º 3
0
        SerializableLocalizationObjectPair DrawLanguageValue(Rect position, SerializableLocalizationObjectPair item)
        {
            float fullWindowWidth = position.width + 28;

            position.width = fullWindowWidth;

            if (GUI.Button(listColumns.GetColumnPosition(position, "Копия"), "Из корня"))     //Copy Root
            {
                if (undoManager != null)
                {
                    undoManager.ForceDirty();
                }

                item.changedValue = new LocalizedObject(rootValues[item.keyValue]);

                GUIUtility.keyboardControl = 0;
            }
            if (item.changedValue.ObjectType == LocalizedObjectType.STRING && canLanguageBeTranslated &&
                translateFromLanguageValue != 0 &&
                translateFromDictionary != null && translateFromDictionary[item.keyValue].TextValue != null &&
                translateFromDictionary[item.keyValue].TextValue != string.Empty)
            {
                if (GUI.Button(listColumns.GetColumnPosition(position, "Перевод"), "Перевод"))          //Translate
                {
                    automaticTranslator.TranslateText(OnTextTranslated, item.keyValue, translateFromDictionary[item.keyValue].TextValue,
                                                      translateFromLanguage, currentCultureInfo.languageCode);
                }
            }
            else
            {
                GUI.Label(listColumns.GetColumnPosition(position, "Перевод"), "Перевод");           //Translate
            }

            EditorGUI.SelectableLabel(listColumns.GetColumnPosition(position, "Ключ"), item.keyValue);                              //Key
            EditorGUI.SelectableLabel(listColumns.GetColumnPosition(position, "Комментарий"), rootValues[item.keyValue].TextValue); //Comment

            if (item.changedValue.ObjectType != LocalizedObjectType.STRING && otherAvailableLanguageCodes.Count > 0)
            {
                bool overrideLang = EditorGUI.Toggle(listColumns.GetColumnPosition(position, "Переопределить"), item.changedValue.OverrideLocalizedObject);           //Override
                if (overrideLang != item.changedValue.OverrideLocalizedObject)
                {
                    if (undoManager != null)
                    {
                        undoManager.ForceDirty();
                    }

                    item.changedValue.OverrideLocalizedObject = overrideLang;

                    if (overrideLang)
                    {
                        item.changedValue.OverrideObjectLanguageCode = otherAvailableLanguageCodes[0];
                    }
                }
            }
            else
            {
                GUI.Label(listColumns.GetColumnPosition(position, "Переопределить"), "-");            //Override
            }

            Rect newPosition = listColumns.GetColumnPosition(position, "Значение");        //Value

            bool setDirty = false;

            if (!item.changedValue.OverrideLocalizedObject)
            {
                if (item.changedValue.ObjectType == LocalizedObjectType.STRING)
                {
                    string newTextValue = EditorGUI.TextArea(newPosition, item.changedValue.TextValue);
                    if (newTextValue != item.changedValue.TextValue)
                    {
                        setDirty = true;
                        item.changedValue.TextValue = newTextValue;
                    }
                }
                else if (item.changedValue.ObjectType == LocalizedObjectType.AUDIO)
                {
                    AudioClip newAudioValue = (AudioClip)EditorGUI.ObjectField(newPosition,
                                                                               item.changedValue.ThisAudioClip,
                                                                               typeof(AudioClip), false);
                    if (newAudioValue != item.changedValue.ThisAudioClip)
                    {
                        setDirty = true;
                        item.changedValue.ThisAudioClip = newAudioValue;
                    }
                }
                else if (item.changedValue.ObjectType == LocalizedObjectType.GAME_OBJECT)
                {
                    GameObject newGameObjectValue = (GameObject)EditorGUI.ObjectField(newPosition,
                                                                                      item.changedValue.ThisGameObject,
                                                                                      typeof(GameObject), false);

                    if (newGameObjectValue != item.changedValue.ThisGameObject)
                    {
                        setDirty = true;
                        item.changedValue.ThisGameObject = newGameObjectValue;
                    }
                }
                else if (item.changedValue.ObjectType == LocalizedObjectType.TEXTURE)
                {
                    Texture newTextureValue = (Texture)EditorGUI.ObjectField(newPosition,
                                                                             item.changedValue.ThisTexture,
                                                                             typeof(Texture), false);
                    if (newTextureValue != item.changedValue.ThisTexture)
                    {
                        setDirty = true;
                        item.changedValue.ThisTexture = newTextureValue;
                    }
                }
                else if (item.changedValue.ObjectType == LocalizedObjectType.TEXT_ASSET)
                {
                    TextAsset newTextAssetValue = (TextAsset)EditorGUI.ObjectField(newPosition,
                                                                                   item.changedValue.ThisTextAsset,
                                                                                   typeof(TextAsset), false);
                    if (newTextAssetValue != item.changedValue.ThisTextAsset)
                    {
                        setDirty = true;
                        item.changedValue.ThisTextAsset = newTextAssetValue;
                    }
                }
                else if (item.changedValue.ObjectType == LocalizedObjectType.FONT)
                {
                    Font newFontValue = (Font)EditorGUI.ObjectField(newPosition,
                                                                    item.changedValue.Font,
                                                                    typeof(Font), false);
                    if (newFontValue != item.changedValue.Font)
                    {
                        setDirty = true;
                        item.changedValue.Font = newFontValue;
                    }
                }
            }
            else
            {
                if (otherAvailableLanguageCodes.Count > 0)
                {
                    int selectedIndex = -1;
                    for (int i = 0; i < otherAvailableLanguageCodes.Count; ++i)
                    {
                        if (otherAvailableLanguageCodes[i] == item.changedValue.OverrideObjectLanguageCode)
                        {
                            selectedIndex = i;
                            break;
                        }
                    }

                    if (selectedIndex == -1)
                    {
                        selectedIndex = 0;
                        item.changedValue.OverrideObjectLanguageCode = otherAvailableLanguageCodes[selectedIndex];
                        setDirty = true;
                    }
                    int newIndex = EditorGUI.Popup(newPosition, selectedIndex, otherAvailableLanguageCodesArray);

                    if (newIndex != selectedIndex)
                    {
                        item.changedValue.OverrideObjectLanguageCode = otherAvailableLanguageCodes[newIndex];
                        setDirty = true;
                    }
                }
                else
                {
                    //There are no languages to steal from, disable the override.
                    item.changedValue.OverrideLocalizedObject = false;
                    setDirty = true;
                }
            }

            if (undoManager != null && setDirty)
            {
                undoManager.ForceDirty();
            }
            return(item);
        }
    void OnPostprocessModel(GameObject g)
    {
        string assetFolder = Path.GetDirectoryName(assetPath);

        //if (assetFolder == "Assets/scenes/IES/Stadsmodell")
        if (assetFolder.Contains("Assets/Models/Maps"))
        {
            //Renderer rend = g.GetComponent<Renderer>();

            ////rend.receiveShadows = false;

            Debug.Log("name: " + Path.GetFileNameWithoutExtension(assetPath));
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetPath);

            //string textureName = assetFolder + "/" + fileNameWithoutExtension + "_0.jpg";
            //Texture2D t = (Texture2D)AssetDatabase.LoadAssetAtPath(textureName, typeof(Texture2D));
            ////rend.sharedMaterial.name = fileNameWithoutExtension;
            //rend.material.mainTexture = t;

            // XML
            string    xmlFileName = assetFolder + "/" + fileNameWithoutExtension + ".xml";
            TextAsset xmlFile     = (TextAsset)AssetDatabase.LoadAssetAtPath(xmlFileName, typeof(TextAsset));
            if (xmlFile == null)
            {
                Debug.Log("Couldn't find textasset : " + xmlFileName);
            }
            XmlDocument xmlDoc = loadXml(xmlFile);

            XmlNodeList originNodes = xmlDoc.GetElementsByTagName("Origin");

            float x = 0f;
            float y = 0f;
            float z = 0f;

            foreach (XmlNode originNode in originNodes)
            {
                //Debug.Log("Origin info: " + originInfo);
                XmlNodeList axisNodes = originNode.ChildNodes;
                foreach (XmlNode axis in axisNodes)
                {
                    if (axis.Name == "x")
                    {
                        //Debug.Log("X value: " + axis.InnerText);
                        double v       = 0.0;
                        bool   parseOk = Double.TryParse(axis.InnerText, out v);
                        if (parseOk)
                        {
                            x = (float)(v - xRoot);
                        }
                        else
                        {
                            Debug.Log("Couldn't parse value " + axis.InnerText);
                        }
                    }
                    if (axis.Name == "y")
                    {
                        //Debug.Log("X value: " + axis.InnerText);
                        double v       = 0.0;
                        bool   parseOk = Double.TryParse(axis.InnerText, out v);
                        if (parseOk)
                        {
                            y = (float)(v - yRoot);
                        }
                        else
                        {
                            Debug.Log("Couldn't parse value " + axis.InnerText);
                        }
                    }
                    if (axis.Name == "z")
                    {
                        //Debug.Log("X value: " + axis.InnerText);
                        double v       = 0.0;
                        bool   parseOk = Double.TryParse(axis.InnerText, out v);
                        if (parseOk)
                        {
                            z = (float)(zRoot - v);
                            //z = (float)(v);
                        }
                        else
                        {
                            Debug.Log("Couldn't parse value " + axis.InnerText);
                        }
                    }
                }
            }

            g.transform.localPosition = new Vector3(x, y, z);
            g.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
        }
    }
    static AtlasAsset IngestSpineAtlas(TextAsset atlasText)
    {
        if (atlasText == null)
        {
            Debug.LogWarning("Atlas source cannot be null!");
            return(null);
        }

        string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", "");
        string assetPath   = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText));

        string atlasPath = assetPath + "/" + primaryName + "_Atlas.asset";

        AtlasAsset atlasAsset = (AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset));


        if (atlasAsset == null)
        {
            atlasAsset = AtlasAsset.CreateInstance <AtlasAsset>();
        }

        atlasAsset.atlasFile = atlasText;

        //strip CR
        string atlasStr = atlasText.text;

        atlasStr = atlasStr.Replace("\r", "");

        string[]      atlasLines = atlasStr.Split('\n');
        List <string> pageFiles  = new List <string>();

        for (int i = 0; i < atlasLines.Length - 1; i++)
        {
            if (atlasLines[i].Length == 0)
            {
                pageFiles.Add(atlasLines[i + 1]);
            }
        }

        atlasAsset.materials = new Material[pageFiles.Count];

        for (int i = 0; i < pageFiles.Count; i++)
        {
            string    texturePath = assetPath + "/" + pageFiles[i];
            Texture2D texture     = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));

            TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
            texImporter.textureFormat       = TextureImporterFormat.AutomaticTruecolor;
            texImporter.mipmapEnabled       = false;
            texImporter.alphaIsTransparency = false;
            texImporter.maxTextureSize      = 2048;

            EditorUtility.SetDirty(texImporter);
            AssetDatabase.ImportAsset(texturePath);
            AssetDatabase.SaveAssets();

            string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]);

            //because this looks silly
            if (pageName == primaryName && pageFiles.Count == 1)
            {
                pageName = "Material";
            }

            string   materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
            Material mat          = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));

            if (mat == null)
            {
                mat = new Material(Shader.Find(defaultShader));
                AssetDatabase.CreateAsset(mat, materialPath);
            }

            mat.mainTexture = texture;
            EditorUtility.SetDirty(mat);

            AssetDatabase.SaveAssets();

            atlasAsset.materials[i] = mat;
        }

        if (AssetDatabase.GetAssetPath(atlasAsset) == "")
        {
            AssetDatabase.CreateAsset(atlasAsset, atlasPath);
        }
        else
        {
            atlasAsset.Reset();
        }

        AssetDatabase.SaveAssets();

        return((AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset)));
    }
Ejemplo n.º 6
0
 public CheckerResult(TextAsset script)
 {
     this.script = script;
     this.state  = State.NotTested;
 }
Ejemplo n.º 7
0
        public static Dlg Load(TextAsset xmlFile)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Dlg));

            return(xmlSerializer.Deserialize(new StringReader(xmlFile.text)) as Dlg);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// This function will parse the device parameters from a device descriptor json file.
 ///
 /// Returns a DeviceDescriptor object containing stored json values.
 /// </summary>
 public DeviceDescriptor GetDisplayParameters(TextAsset jsonDescriptor)
 {
     _deviceDescriptorJson = jsonDescriptor.text;
     return GetDeviceDescription();
 }
Ejemplo n.º 9
0
    public TextAsset LoadCSV(string csvName)
    {
        TextAsset csvObject = Resources.Load("CSV/" + csvName) as TextAsset;

        return(csvObject);
    }
Ejemplo n.º 10
0
    public static void Load(TextAsset asset)
    {
        ByteReader byteReader = new ByteReader(asset);

        Localization.Set(asset.name, byteReader.ReadDictionary());
    }
Ejemplo n.º 11
0
 //Constructor
 public XmlParser(TextAsset x)
 {
     xmlFile = x;
     xml     = new XmlDocument();
 }
Ejemplo n.º 12
0
    public static void LoadTiles()
    {
        PrefabTile tile = new PrefabTile();
        TextAsset  txt  = Resources.Load("Meta/Tiles") as TextAsset;

        string[] lines = txt.text.Split("\n"[0]);
        string   s;
        int      n = 0;
        int      t = 0;

        for (int l = 0; l < lines.Length; l++)
        {
            s = lines[l];

            /* Name */
            if (n == 0)
            {
                tile      = new PrefabTile();
                tile.name = s;
            }

            /* Mesh */
            if (n == 1)
            {
                tile.obj = Resources.Load("Models/Tiles/" + s.Substring(0, s.Length - 5)) as GameObject;
            }

            /* Attribute */
            if (n == 2)
            {
                tile.att = int.Parse(s);
            }

            /* Material */
            if (n == 3)
            {
                tile.mat = int.Parse(s);
            }

            /* Delphi RX */
            if (n == 4)
            {
                tile.d_rx = float.Parse(s);
            }

            /* Delphi RY */
            if (n == 5)
            {
                tile.d_ry = float.Parse(s);
            }

            /* Delphi RZ */
            if (n == 6)
            {
                tile.d_rz = float.Parse(s);
            }

            /* Unity RX */
            if (n == 7)
            {
                tile.u_rx = float.Parse(s);
            }

            /* Unity RY */
            if (n == 8)
            {
                tile.u_ry = float.Parse(s);
            }

            /* Unity RZ */
            if (n == 9)
            {
                tile.u_rz = float.Parse(s);
            }

            /* Delphi Scale */
            if (n == 10)
            {
                tile.d_s = float.Parse(s);
            }

            /* Unity Scale */
            if (n == 11)
            {
                tile.u_s = float.Parse(s);
            }

            /* Increment */
            n++;
            if (n == 12)
            {
                n = 0;
                Manager.instance.prefab_tiles[t] = tile;
                //Debug.Log(Manager.instance.prefab_tiles[t]);
                t++;
            }
        }
    }
Ejemplo n.º 13
0
 public void LoadMap(uint mapId, TextAsset txt)
 {
     this.currentMapId = mapId;
     this.LoadOtherMap(mapId, txt);
 }
    // Use this for initialization
    void Start()
    {
        Debug.Log ("Llamado al metodo START de MenuOfStepsPhase1 - Instancia:" + this.gameObject.GetInstanceID() + " name:" + this.gameObject.name);

        //inicializando variable que controla si todos los items estan en los slots:
        items_ubicados_correctamente = false;

        //inicializando la variable que indica si se ha pedido organizar automaticamente los pasos
        //por el appmanager:
        //steps_organized_from_manager = false;

        //desactivando el tick de orden correcto hasta que se obtenga el orden correcto:
        if (tickCorrectOrder != null)
            tickCorrectOrder.enabled = false;

        //cargando la imagen del tick y del boton warning:
        img_tick = Resources.Load<Sprite> ("Sprites/buttons/tick");
        img_warning = Resources.Load<Sprite> ("Sprites/buttons/warning_order");

        //obteniendo el componente del encabezado de la imagen:
        imagen_header = GameObject.Find ("header_image_menuphase1");
        if (imagen_header != null) {
            Debug.Log ("La imagen del HEADER es: " + image_header_phase1);
            sprite_image_header_phase1 = Resources.Load<Sprite> (image_header_phase1);
            imagen_header.GetComponent<Image>().sprite = sprite_image_header_phase1;
        }

        //obteniendo el componente text que se llama titulo en el prefab:
        //titulo_object = GameObject.Find ("title_menu_steps_phase1_text");
        if (titulo_object != null) {
            Debug.LogError ("Se va a cambiar el TITULO de la interfaz es: " + titulo);
            titulo_object.GetComponent<Text> ().text = titulo;
        } else {
            Debug.LogError("ERROR: El objeto que debe mostrar el titulo de la interfaz es NULL");
        }

        //colocando el texto de la introduccion:
        introduction_object = GameObject.Find ("introduction_steps_of_phase1_interface");
        if (introduction_object != null) {
            Debug.LogError("Se va a cambiar el texto de la INTRODUCCION con path=" + introduction_text_path);
            introduction_asset = Resources.Load(introduction_text_path) as TextAsset;
            introduction_object.GetComponent<Text>().text = introduction_asset.text;
            Debug.LogError("Despues de cambiar el texto de la intro: " + introduction_asset.text);
        }

        //accion regresar en el boton
        if(regresar != null){
            Debug.LogError("Se agrega la accion al boton REGRESAR");
            regresar.onClick.AddListener(()=>{ActionButton_goBackToMenuPhases();});
        }

        //accion ir al Step1 del Phase

        //colocando las imagenes de las fases despues del encabezado (guia del proceso completo para los estudiantes)
        //image_phase1_object = GameObject.Find ("image_phase1");
        if (image_phase1_object != null) {
            image_phase1_sprite = Resources.Load<Sprite> (image_phase1_path);
            image_phase1_object.GetComponent<Image> ().sprite = image_phase1_sprite;
        } else {
            Debug.LogError ("---> Error: El objeto que debe mostrar la imagen de FASE en el encabezado es NULL");
        }

        //image_phase2_object = GameObject.Find ("image_phase2");
        if (image_phase2_object != null) {
            image_phase2_sprite = Resources.Load<Sprite>(image_phase2_path);
            image_phase2_object.GetComponent<Image>().sprite = image_phase2_sprite;
        }else {
            Debug.LogError ("---> Error: El objeto que debe mostrar la imagen de FASE en el encabezado es NULL");
        }

        //image_phase3_object = GameObject.Find ("image_phase3");
        if (image_phase3_object != null) {
            image_phase3_sprite = Resources.Load<Sprite>(image_phase3_path);
            image_phase3_object.GetComponent<Image>().sprite = image_phase3_sprite;
        }else {
            Debug.LogError ("---> Error: El objeto que debe mostrar la imagen de FASE en el encabezado es NULL");
        }

        //image_phase4_object = GameObject.Find ("image_phase4");
        if (image_phase4_object != null) {
            image_phase4_sprite = Resources.Load<Sprite>(image_phase4_path);
            image_phase4_object.GetComponent<Image>().sprite = image_phase4_sprite;
        }else {
            Debug.LogError ("---> Error: El objeto que debe mostrar la imagen de FASE en el encabezado es NULL");
        }

        //image_phase5_object = GameObject.Find ("image_phase5");
        if (image_phase5_object != null) {
            image_phase5_sprite = Resources.Load<Sprite>(image_phase5_path);
            image_phase5_object.GetComponent<Image>().sprite = image_phase5_sprite;
        }else {
            Debug.LogError ("---> Error: El objeto que debe mostrar la imagen de FASE en el encabezado es NULL");
        }

        //image_phase6_object = GameObject.Find ("image_phase6");
        if (image_phase6_object != null) {
            image_phase6_sprite = Resources.Load<Sprite>(image_phase6_path);
            image_phase6_object.GetComponent<Image>().sprite = image_phase6_sprite;
        }

        if (capoCarroButton != null) {
            image_button_sprite_uno = Resources.Load<Sprite> (image_uno_capo_carro);
            capoCarroButton.GetComponent<Image>().sprite = image_button_sprite_uno;
            ////Agregando la accion para ir al step1 - phase 1 (buscar capo del carro):
            capoCarroButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step1();});
            drag_controller = capoCarroButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_one;
        }

        if (limpiezaButton != null) {
            image_button_sprite_dos = Resources.Load<Sprite> (image_dos_limpieza);
            limpiezaButton.GetComponent<Image>().sprite = image_button_sprite_dos;
            //Agregando la accion para ir al conjunto de actividades (2. limpieza):
            limpiezaButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step2();});
            drag_controller = limpiezaButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_two;
        }

        if (secadoButton != null) {
            image_button_sprite_tres = Resources.Load<Sprite> (image_tres_secado);
            secadoButton.GetComponent<Image>().sprite = image_button_sprite_tres;
            //Agregando la accion para ir al conjunto de actividades (3. secado):
            secadoButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step3();});
            drag_controller = secadoButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_three;
        }

        if (irregularidadesButton != null) {
            image_button_sprite_cuatro = Resources.Load<Sprite> (image_cuatro_irregularidades);
            irregularidadesButton.GetComponent<Image>().sprite = image_button_sprite_cuatro;
            //Agregando la accion para ir al conjunto de actividades (4. localizar irregularidades):
            irregularidadesButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step4();});
            drag_controller = irregularidadesButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_four;
        }

        if (corregirButton != null) {
            image_button_sprite_cinco = Resources.Load<Sprite> (image_cinco_corregir);
            corregirButton.GetComponent<Image>().sprite = image_button_sprite_cinco;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            corregirButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step5();});
            drag_controller = corregirButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_five;
        }

        if (desengrasadoButton != null) {
            image_button_sprite_seis = Resources.Load<Sprite> (image_seis_desengrasar);
            desengrasadoButton.GetComponent<Image>().sprite = image_button_sprite_seis;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            desengrasadoButton.onClick.AddListener(()=>{ActionButton_goToActivitiesPhase1Step6();});
            drag_controller = desengrasadoButton.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_six;
        }

        //colocando los textos en los botones:
        if(textUnocapoCarro != null){
            textUnocapoCarro.text = this.button_uno_text_capo_carro;
        }

        if(textDosLimpieza != null){
            textDosLimpieza.text = this.button_dos_text_limpieza;
        }

        if(textTresSecado != null){
            textTresSecado.text = this.button_tres_text_secado;
        }

        if(textCuatroIrregularidades != null){
            textCuatroIrregularidades.text = this.button_cuatro_text_irregularidades;
        }

        if(textCincoCorregir != null){
            textCincoCorregir.text = this.button_cinco_text_corregir;
        }

        if(textSeisDesengrasar != null){
            textSeisDesengrasar.text = this.button_seis_text_desengrasar;
        }

        //llamado al metodo hasChanged para verificar si hay algun cambio los slots de pasos:
        HasChanged ();
    }
Ejemplo n.º 15
0
    //--CSVからカードデータを読み込む関数
    void LoadFromCSV(string csvFimeName)
    {
        TextAsset       csvTextAsset       = (TextAsset)Resources.Load("CSV/" + csvFimeName);   //CSVファイルをTextAssetとして読み込む
        StringReader    stringReader       = new StringReader(csvTextAsset.text);               //csvTextAssetのテキストを読むStringReaderを生成
        List <string[]> csvStringArrayList = new List <string[]> ();                            //CSVの各値を列ごとにstring配列で格納するための変数

        //カンマごとに区切って配列へ格納-------------------
        while (stringReader.Peek() > -1)
        {
            string line = stringReader.ReadLine();
            csvStringArrayList.Add(line.Split(','));
        }
        //------------------------------------------------
        //CSVのデータを_cardDatasへ格納-------------------------------------------------------
        for (int i = 0; i < csvStringArrayList.Count; i++)
        {
            if (i > 0)                //i==0は各項目名なので除く
            {
                CardData cardData = new CardData();
                cardData._id           = int.Parse(csvStringArrayList [i] [0]);
                cardData._attack       = int.Parse(csvStringArrayList [i] [1]);
                cardData._maxToughness = int.Parse(csvStringArrayList [i] [2]);
                cardData._toughness    = cardData._maxToughness;
                //CSVデータからList<Field.DIRECTION>を作る--------------------------------------------
                int directionOfTravelData = int.Parse(csvStringArrayList [i] [3]);
                List <Field.DIRECTION> directionOfTravelList = new List <Field.DIRECTION> ();
                while (directionOfTravelData != 0)
                {
                    Field.DIRECTION fieldDirection = (Field.DIRECTION)(directionOfTravelData % 10);
                    directionOfTravelList.Add(fieldDirection);
                    directionOfTravelData /= 10;
                }
                //-----------------------------------------------------------------------------------
                cardData._directionOfTravel = directionOfTravelList;
                cardData._effect_type       = (CardData.EFFECT_TYPE) int.Parse(csvStringArrayList [i] [4]);
                cardData._effect_value      = int.Parse(csvStringArrayList [i] [5]);
                //CSVデータからList<Field.DIRECTION>を作る--------------------------------------------
                int effectDirectionData = int.Parse(csvStringArrayList [i] [6]);
                List <Field.DIRECTION> effectDirecionList = new List <Field.DIRECTION> ();
                while (effectDirectionData != 0)
                {
                    Field.DIRECTION fieldDirection = (Field.DIRECTION)(effectDirectionData % 10);
                    effectDirecionList.Add(fieldDirection);
                    effectDirectionData /= 10;
                }
                //------------------------------------------------------------------------------------
                cardData._effect_direction     = effectDirecionList;
                cardData._effect_distance      = int.Parse(csvStringArrayList [i] [7]);
                cardData._necessaryMP          = int.Parse(csvStringArrayList [i] [8]);
                cardData._necessaryAP          = int.Parse(csvStringArrayList [i] [9]);
                cardData._necessaryAPForEffect = int.Parse(csvStringArrayList [i] [10]);
                //一度改行部分で分割して再び結合させる(改行させるため)--------------------------
                string[] cardTextList = csvStringArrayList [i] [11].Split(';');
                string   cardText     = "";
                for (int j = 0; j < cardTextList.Length; j++)
                {
                    cardText += cardTextList [j];
                    if (j < cardTextList.Length - 1)
                    {
                        cardText += "\n";                        //これで改行させる
                    }
                }
                cardData._textString = cardText;
                //----------------------------------------------------------------------------
                _cardDatas.Add(cardData);
            }
        }
        //------------------------------------------------------------------------------------
    }
    // Use this for initialization
    void Start()
    {
        //inicializando variable que controla si todos los items estan en los slots:
        items_ubicados_correctamente = false;

        //desactivando el tick de orden correcto hasta que se obtenga el orden correcto:
        if (tickCorrectOrder != null)
            tickCorrectOrder.enabled = false;

        //cargando la imagen del warning que se muestra en cambio del tick cuando el orden no es correcto:
        img_warning = Resources.Load<Sprite> ("Sprites/buttons/warning_order");

        //cargando la imagen del tick:
        img_tick = Resources.Load<Sprite> ("Sprites/buttons/tick");

        //lamado al metodo que verifica si los items estan ubicados correctamente o no:

        //obteniendo el componente text que se llama titulo en el prefab:
        titulo_object = GameObject.Find ("title_process_phases_interface");
        if (titulo_object != null) {
            Debug.LogError("Se va a cambiar el titulo de la interfaz!!");
            titulo_object.GetComponent<Text>().text = titulo;
        }

        introduction_object = GameObject.Find ("introduction_process_phases_interface");
        if (introduction_object != null) {
            Debug.LogError("Se va a cambiar el texto central!!");
            introduction_asset = Resources.Load(introduction_text_path) as TextAsset;
            introduction_object.GetComponent<Text>().text = introduction_asset.text;

        }

        if (limpiezaButton != null) {
            image_button_sprite_uno = Resources.Load<Sprite> (image_uno_limpieza);
            limpiezaButton.GetComponent<Image>().sprite = image_button_sprite_uno;
            //Agregando la accion del boton: esta accion apunta al Action definido desde AppManager
            limpiezaButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase1();});
            drag_controller = limpiezaButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_one;
            Debug.Log("CanvasProcessManagerEval: Se asigna el numero de fase: " + phase_number_button_one + " al btn LIMPIEZA");
        }

        if (matizadoButton != null) {
            image_button_sprite_dos = Resources.Load<Sprite> (image_dos_matizado);
            matizadoButton.GetComponent<Image>().sprite = image_button_sprite_dos;
            matizadoButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase2();});
            drag_controller = matizadoButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_two;
        }

        if (masilladoButton != null) {
            image_button_sprite_tres = Resources.Load<Sprite> (image_tres_masillado);
            masilladoButton.GetComponent<Image>().sprite = image_button_sprite_tres;
            masilladoButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase3();});
            drag_controller = masilladoButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_three;
        }

        if (aparejadoButton != null) {
            image_button_sprite_cuatro = Resources.Load<Sprite> (image_cuatro_aparejado);
            aparejadoButton.GetComponent<Image>().sprite = image_button_sprite_cuatro;
            aparejadoButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase4();});
            drag_controller = aparejadoButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_four;
        }

        if (pintadoButton != null) {
            image_button_sprite_cinco = Resources.Load<Sprite> (image_cinco_pintado);
            pintadoButton.GetComponent<Image>().sprite = image_button_sprite_cinco;
            pintadoButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase5();});
            drag_controller = pintadoButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_five;
        }

        if (barnizadoButton != null) {
            image_button_sprite_seis = Resources.Load<Sprite> (image_seis_barnizado);
            barnizadoButton.GetComponent<Image>().sprite = image_button_sprite_seis;
            barnizadoButton.onClick.AddListener(()=>{ActionButton_goToMenuStepsOfPhase6();});
            drag_controller = barnizadoButton.GetComponent<DragBehaviour>();
            if(drag_controller != null)
                drag_controller.phase_number = phase_number_button_six;
        }

        if (regresar != null) {
            regresar.onClick.AddListener(()=>{ActionButton_goToSelectionMode();});
        }

        //colocando los textos en los botones:
        if(textUnoLimpieza != null){
            textUnoLimpieza.text = this.button_uno_text_limpieza;
        }

        if(textDosMatizado != null){
            textDosMatizado.text = this.button_dos_text_matizado;
        }

        if(textTresMasillado != null){
            textTresMasillado.text = this.button_tres_text_masillado;
        }

        if(textCuatroAparejado != null){
            textCuatroAparejado.text = this.button_cuatro_text_aparejado;
        }

        if(textCincoPintado != null){
            textCincoPintado.text = this.button_cinco_text_pintado;
        }

        if(textSeisBarnizado != null){
            textSeisBarnizado.text = this.button_seis_text_barnizado;
        }
        /*
        //Agrrgando los textos que van dentro de los slots donde se organizan:
        if (slot1_Ordenado != null)
            this.slot1_Ordenado.text = texto_slot1_ordenar;

        if (slot2_Ordenado != null)
            this.slot2_Ordenado.text = texto_slot2_ordenar;

        if (slot3_Ordenado != null)
            this.slot3_Ordenado.text = texto_slot3_ordenar;

        if (slot4_Ordenado != null)
            this.slot4_Ordenado.text = texto_slot4_ordenar;

        if (slot5_Ordenado != null)
            this.slot5_Ordenado.text = texto_slot5_ordenar;

        if (slot6_Ordenado != null)
            this.slot6_Ordenado.text = texto_slot6_ordenar;
        */

        HasChanged ();
    }
Ejemplo n.º 17
0
    public void LoadLowData()
    {
        {
            TextAsset data = Resources.Load("TestJson/Partner_PartnerData", typeof(TextAsset)) as TextAsset;
            StringReader sr = new StringReader(data.text);
            string strSrc = sr.ReadToEnd();
            JSONObject PartnerData = new JSONObject(strSrc);

            for (int i = 0; i < PartnerData.list.Count; i++)
            {
                PartnerDataInfo tmpInfo = new PartnerDataInfo();
                tmpInfo.Id = (uint)PartnerData[i]["Id_ui"].n;
                tmpInfo.NameId = (uint)PartnerData[i]["NameId_ui"].n;
                tmpInfo.DescriptionId = (uint)PartnerData[i]["DescriptionId_ui"].n;
                tmpInfo.Type = (byte)PartnerData[i]["Type_b"].n;
                tmpInfo.Class = (byte)PartnerData[i]["Class_b"].n;
                tmpInfo.AniId = (uint)PartnerData[i]["AniId_ui"].n;
                tmpInfo.prefab = PartnerData[i]["prefab_c"].str;
                tmpInfo.LeftWeaDummy = PartnerData[i]["LeftWeaDummy_c"].str;
                tmpInfo.RightWeaDummy = PartnerData[i]["RightWeaDummy_c"].str;
                tmpInfo.PortraitId = PartnerData[i]["PortraitId_c"].str;
                tmpInfo.AiType = (byte)PartnerData[i]["AiType_b"].n;
                tmpInfo.Quality = (byte)PartnerData[i]["Quality_b"].n;
                tmpInfo.ShardIdx = (uint)PartnerData[i]["ShardIdx_ui"].n;
                tmpInfo.NeedShardValue = (ushort)PartnerData[i]["NeedShardValue_us"].n;
                tmpInfo.PaybackValue = (ushort)PartnerData[i]["PaybackValue_us"].n;
                tmpInfo.QualityUpItem = (uint)PartnerData[i]["QualityUpItem_ui"].n;
                tmpInfo.QualityUpItemCount = (uint)PartnerData[i]["QualityUpItemCount_ui"].n;
                tmpInfo.QualityUpNeedGold = (uint)PartnerData[i]["QualityUpNeedGold_ui"].n;
                tmpInfo.Speed = (byte)PartnerData[i]["Speed_b"].n;
                tmpInfo.Weight = (float)PartnerData[i]["Weight_f"].n;
                tmpInfo.BaseHp = (uint)PartnerData[i]["BaseHp_ui"].n;
                tmpInfo.BaseAtk = (uint)PartnerData[i]["BaseAtk_ui"].n;
                tmpInfo.BaseHit = (uint)PartnerData[i]["BaseHit_ui"].n;
                tmpInfo.BaseAvoid = (uint)PartnerData[i]["BaseAvoid_ui"].n;
                tmpInfo.BaseCriticalRate = (uint)PartnerData[i]["BaseCriticalRate_ui"].n;
                tmpInfo.BaseCriticalResist = (uint)PartnerData[i]["BaseCriticalResist_ui"].n;
                tmpInfo.BaseCriticalDamage = (uint)PartnerData[i]["BaseCriticalDamage_ui"].n;
                tmpInfo.BaseLifeSteal = (uint)PartnerData[i]["BaseLifeSteal_ui"].n;
                tmpInfo.BaseIgnoreAtk = (uint)PartnerData[i]["BaseIgnoreAtk_ui"].n;
                tmpInfo.BaseDamageDown = (uint)PartnerData[i]["BaseDamageDown_ui"].n;
                tmpInfo.BaseDamageDownRate = (uint)PartnerData[i]["BaseDamageDownRate_ui"].n;
                tmpInfo.BaseSuperArmor = (uint)PartnerData[i]["BaseSuperArmor_ui"].n;
                tmpInfo.SuperArmorRecoveryTime = (uint)PartnerData[i]["SuperArmorRecoveryTime_ui"].n;
                tmpInfo.SuperArmorRecoveryRate = (uint)PartnerData[i]["SuperArmorRecoveryRate_ui"].n;
                tmpInfo.SuperArmorRecovery = (uint)PartnerData[i]["SuperArmorRecovery_ui"].n;
                tmpInfo.LevelUpHp = (uint)PartnerData[i]["LevelUpHp_ui"].n;
                tmpInfo.LevelUpAtk = (uint)PartnerData[i]["LevelUpAtk_ui"].n;
                tmpInfo.LevelAvoidRate = (uint)PartnerData[i]["LevelAvoidRate_ui"].n;
                tmpInfo.LevelHitRate = (uint)PartnerData[i]["LevelHitRate_ui"].n;
                tmpInfo.LevelUpSuperArmor = (uint)PartnerData[i]["LevelUpSuperArmor_ui"].n;
                tmpInfo.skill0 = (uint)PartnerData[i]["skill0_ui"].n;
                tmpInfo.skill1 = (uint)PartnerData[i]["skill1_ui"].n;
                tmpInfo.skill2 = (uint)PartnerData[i]["skill2_ui"].n;
                tmpInfo.skill3 = (uint)PartnerData[i]["skill3_ui"].n;
                tmpInfo.skill4 = (uint)PartnerData[i]["skill4_ui"].n;
                tmpInfo.QualityUpId = (uint)PartnerData[i]["QualityUpId_ui"].n;

                PartnerDataInfoDic.Add(tmpInfo.Id, tmpInfo);
            }
        }



        {
            TextAsset data = Resources.Load("TestJson/Partner_PartnerScale", typeof(TextAsset)) as TextAsset;
            StringReader sr = new StringReader(data.text);
            string strSrc = sr.ReadToEnd();
            JSONObject PartnerScale = new JSONObject(strSrc);

            for (int i = 0; i < PartnerScale.list.Count; i++)
            {
                PartnerScaleInfo tmpInfo = new PartnerScaleInfo();
                tmpInfo.Id = (uint)PartnerScale[i]["Id_ui"].n;
                tmpInfo.prefab = PartnerScale[i]["prefab_c"].str;
                tmpInfo._x = (float)PartnerScale[i]["x_pos_f"].n;
                tmpInfo._y = (float)PartnerScale[i]["y_pos_f"].n;
                tmpInfo.rotate_x = (float)PartnerScale[i]["x_rotate_pos_f"].n;
                tmpInfo.rotate_y = (float)PartnerScale[i]["y_rotate_pos_f"].n;
                tmpInfo.scale = (float)PartnerScale[i]["scale_f"].n;
                tmpInfo.panel_name = PartnerScale[i]["panel_name"].str;

                PartnerScaleInfoList.Add(tmpInfo);
            }
        }

    }
Ejemplo n.º 18
0
        public static void PreloadWrap <K1, K2, V>(Dictionary <K1, Dictionary <K2, V> > maps, TextAsset asset,
                                                   MonoBehaviour mono,
                                                   Action <IDictionary> onEnd, Action <float> onProcess) where V : ConfigBase <K2>, new()
        {
            if (maps == null || asset == null || mono == null)
            {
                if (onEnd != null)
                {
                    onEnd(null);
                }
                return;
            }

            PreloadWrap <K1, K2, V>(maps, asset.bytes, mono, onEnd, onProcess);
        }
Ejemplo n.º 19
0
    private static string Load(string filePath)
    {
        TextAsset textFile = Resources.Load(filePath) as TextAsset;

        return(textFile.text);
    }
Ejemplo n.º 20
0
        // Validates a single script.
        ValidationMessage[] ValidateFile(TextAsset script, Analysis.Context analysisContext, out CheckerResult.State result)
        {
            // The list of messages we got from the compiler.
            var messageList = new List <ValidationMessage>();

            // A dummy variable storage; it won't be used, but Dialogue
            // needs it.
            var variableStorage = new Yarn.MemoryVariableStore();

            // The Dialog object is the compiler.
            var dialog = new Dialogue(variableStorage);

            // Whether compilation failed or not; this will be
            // set to true if any error messages are returned.
            bool failed = false;

            // Called when we get an error message. Convert this
            // message into a ValidationMessage and store it;
            // additionally, mark that this file failed compilation
            dialog.LogErrorMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Error;
                msg.message = message;
                messageList.Add(msg);

                // any errors means this validation failed
                failed = true;
            };

            // Called when we get an error message. Convert this
            // message into a ValidationMessage and store it
            dialog.LogDebugMessage = delegate(string message) {
                var msg = new ValidationMessage();
                msg.type    = MessageType.Info;
                msg.message = message;
                messageList.Add(msg);
            };

            // Attempt to compile this script. Any exceptions will result
            // in an error message
            try {
                // TODO: update for Yarn 1.0
                //dialog.LoadString(script.text,script.name);
            } catch (System.Exception e) {
                dialog.LogErrorMessage(e.Message);
            }

            // Once compilation has finished, run the analysis on it
            dialog.Analyse(analysisContext);

            // Did it succeed or not?
            if (failed)
            {
                result = CheckerResult.State.Failed;
            }
            else
            {
                result = CheckerResult.State.Passed;
            }

            // All done.
            return(messageList.ToArray());
        }
Ejemplo n.º 21
0
 // Start is called before the first frame update
 void Start()
 {
     theDialog = GetComponentsInParent <TextAsset>();
     textNum   = 0;
     theText   = theDialog[textNum];
 }
Ejemplo n.º 22
0
 public static TextTable Parse(TextAsset asset)
 {
     return(Parse(new StringReader(asset.text)));
 }
Ejemplo n.º 23
0
 public DialogBox(TextAsset[] theDialog, int textNum, TextAsset theText)
 {
     this.theDialog = theDialog;
     this.textNum   = textNum;
     this.theText   = theText;
 }
Ejemplo n.º 24
0
    unsafe List <(Texture2D, int)> LoadAnimation(string loadPath)
    {
        List <ValueTuple <Texture2D, int> > ret = new List <ValueTuple <Texture2D, int> >();
        TextAsset textasset = Resources.Load <TextAsset>(loadPath);

        byte[] bytes = textasset.bytes;
        WebPAnimDecoderOptions option = new WebPAnimDecoderOptions
        {
            use_threads = 1,
            color_mode  = WEBP_CSP_MODE.MODE_RGBA
        };

        Demux.WebPAnimDecoderOptionsInit(ref option);
        fixed(byte *p = bytes)
        {
            IntPtr   ptr      = (IntPtr)p;
            WebPData webpdata = new WebPData
            {
                bytes = ptr,
                size  = new UIntPtr((uint)bytes.Length)
            };
            IntPtr       dec       = Demux.WebPAnimDecoderNew(ref webpdata, ref option);
            WebPAnimInfo anim_info = new WebPAnimInfo();

            Demux.WebPAnimDecoderGetInfo(dec, ref anim_info);

            Debug.LogWarning($"{anim_info.frame_count} {anim_info.canvas_width}/{anim_info.canvas_height}");

            int size = anim_info.canvas_width * 4 * anim_info.canvas_height;

            IntPtr unmanagedPointer = new IntPtr();
            int    timestamp        = 0;

            for (int i = 0; i < anim_info.frame_count; ++i)
            {
                int  result   = Demux.WebPAnimDecoderGetNext(dec, ref unmanagedPointer, ref timestamp);
                int  lWidth   = anim_info.canvas_width;
                int  lHeight  = anim_info.canvas_height;
                bool lMipmaps = false;
                bool lLinear  = false;

                Texture2D texture = new Texture2D(lWidth, lHeight, TextureFormat.RGBA32, lMipmaps, lLinear);
                texture.LoadRawTextureData(unmanagedPointer, size);

                {// Flip updown.
                    // ref: https://github.com/netpyoung/unity.webp/issues/18
                    // ref: https://github.com/webmproject/libwebp/blob/master/src/demux/anim_decode.c#L309
                    Color[] pixels        = texture.GetPixels();
                    Color[] pixelsFlipped = new Color[pixels.Length];
                    for (int y = 0; y < anim_info.canvas_height; y++)
                    {
                        Array.Copy(pixels, y * anim_info.canvas_width, pixelsFlipped, (anim_info.canvas_height - y - 1) * anim_info.canvas_width, anim_info.canvas_width);
                    }
                    texture.SetPixels(pixelsFlipped);
                }

                texture.Apply();
                ret.Add((texture, timestamp));
            }
            Demux.WebPAnimDecoderReset(dec);
            Demux.WebPAnimDecoderDelete(dec);
        }

        return(ret);
    }
Ejemplo n.º 25
0
 public OTXMLDataReader(string id, TextAsset txAsset) : base(id, txAsset)
 {
 }
Ejemplo n.º 26
0
    public static string ReadTextMap()
    {
        mapText = Resources.Load(ProjectPaths.RESOURCES_MAP_SETTINGS + "map_" + GameManager.nextScene.ToString()) as TextAsset;

        return(mapText.text);
    }
Ejemplo n.º 27
0
    private IEnumerator retrieveFileFromPath(string basePath)
    {
        string filePath = System.IO.Path.Combine(basePath, configFileName + fileExtension);

        result = "";

        if (filePath.Contains("://"))
        {
            WWW www = new WWW(filePath);
            yield return(www);

            if (www.error != null)
            {
                result = Resources.Load <TextAsset>(configFileName).text;
            }
            else
            {
                result = www.text;
            }
        }
        else
        {
                        #if !UNITY_WEBPLAYER
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    result = System.IO.File.ReadAllText(filePath);
                }
                if (result.Length < 5)                  //some random lenght more than 0
                {
                    TextAsset textAsset = Resources.Load <TextAsset>(configFileName);
                    result = textAsset.text;
                }
            }
            catch (System.IO.FileNotFoundException e)
            {
                Debug.Log(e.Data);

                result = Resources.Load <TextAsset>(configFileName).text;
            }
            catch (System.IO.IOException e)
            {
                Debug.Log(e.Data);

                result = Resources.Load <TextAsset>(configFileName).text;
            }
                        #endif
        }

        // load xml from computer
        xmlResult = new ConfigReader();
        xmlResult.LoadXml(result);

        // local xml from game
        ConfigReader xmlGame = new ConfigReader();
        xmlGame.LoadXml(Resources.Load <TextAsset>(configFileName).text);

        //check version numbers
        if (xmlResult.GetElementsByTagName("Version").Count == 0)
        {
            Debug.Log("Updating Config.xml from build 'old' to build " + (xmlGame.GetElementsByTagName("Version")[0] as Xml.XmlElement).GetAttribute("build"));
            // update to latest
            cfgUpdate();
        }
        else if (int.Parse((xmlResult.GetElementsByTagName("Version")[0] as Xml.XmlElement).GetAttribute("build")) < int.Parse((xmlGame.GetElementsByTagName("Version")[0] as Xml.XmlElement).GetAttribute("build")))
        {
            Debug.Log("Updating Config.xml from build " + (xmlResult.GetElementsByTagName("Version")[0] as Xml.XmlElement).GetAttribute("build") +
                      " to build " + (xmlGame.GetElementsByTagName("Version")[0] as Xml.XmlElement).GetAttribute("build"));
            // update to latest
            cfgUpdate();
        }

        cfgLoadLevels();
        cfgLoadColors();
        cfgLoadOptions();
        cfgLoadModels();

        loaded = true;
    }
Ejemplo n.º 28
0
    // Token: 0x060002BE RID: 702 RVA: 0x00026DA4 File Offset: 0x00024FA4
    public bool LoadTable(string in_DataName)
    {
        if (!DataManager.Instance.bLoadingTableSuccess)
        {
            return(false);
        }
        bool result = false;

        if (in_DataName.Length == 0)
        {
            DataManager.Instance.bLoadingTableSuccess = false;
            return(result);
        }
        AssetBundle tableAB = DataManager.Instance.GetTableAB();

        if (tableAB == null)
        {
            DataManager.Instance.bLoadingTableSuccess = false;
            return(result);
        }
        TextAsset textAsset = tableAB.Load(in_DataName) as TextAsset;

        if (textAsset == null)
        {
            DataManager.Instance.bLoadingTableSuccess = false;
            return(result);
        }
        Stream stream = new MemoryStream(textAsset.bytes);

        if (stream.Length <= 4L)
        {
            DataManager.Instance.bLoadingTableSuccess = false;
            return(result);
        }
        GCHandle gchandle = GCHandle.Alloc(textAsset.bytes, GCHandleType.Pinned);

        this.BytesIntPtr = gchandle.AddrOfPinnedObject();
        int num  = (int)stream.Length - 4;
        int num2 = Marshal.SizeOf(typeof(R));

        if (num < num2 || num % num2 != 0)
        {
            if (gchandle.IsAllocated)
            {
                gchandle.Free();
                this.BytesIntPtr = IntPtr.Zero;
            }
            stream.Close();
            Resources.UnloadUnusedAssets();
            DataManager.Instance.bLoadingTableSuccess = false;
            return(result);
        }
        this.RecordAmount = num / num2;
        using (BinaryReader binaryReader = new BinaryReader(stream))
        {
            binaryReader.ReadUInt16();
            ushort num3 = binaryReader.ReadUInt16();
            if (this.RecordAmount > (int)num3)
            {
                this.RecordAmount = (int)num3;
            }
            int startIdx = 4 + (this.RecordAmount - 1) * num2;
            this.MaxKey  = GameConstants.ConvertBytesToUShort(textAsset.bytes, startIdx);
            this.MaxKey += 1;
            ushort[] array = new ushort[(int)this.MaxKey];
            Array.Clear(array, 0, (int)this.MaxKey);
            int    num4 = 4;
            ushort num5 = 0;
            while ((int)num5 < this.RecordAmount)
            {
                array[(int)GameConstants.ConvertBytesToUShort(textAsset.bytes, num4)] = num5;
                num4 += num2;
                num5 += 1;
            }
            this.KeyMapIndex = GCHandle.Alloc(array, GCHandleType.Pinned).AddrOfPinnedObject();
            binaryReader.Close();
        }
        stream.Close();
        return(true);
    }
Ejemplo n.º 29
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group from which expanded text ads
        /// are retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupAdService adGroupAdService =
                       (AdGroupAdService)user.GetService(AdWordsService.v201809.AdGroupAdService))
            {
                // Create a selector to select all ads for the specified ad group.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        ResponsiveSearchAd.Fields.Id,
                        AdGroupAd.Fields.Status,
                        ResponsiveSearchAd.Fields.ResponsiveSearchAdHeadlines,
                        ResponsiveSearchAd.Fields.ResponsiveSearchAdDescriptions
                    },
                    ordering = new OrderBy[]
                    {
                        OrderBy.Asc(ResponsiveSearchAd.Fields.Id)
                    },
                    predicates = new Predicate[]
                    {
                        // Restrict the fetch to only the selected ad group id.
                        Predicate.Equals(AdGroupAd.Fields.AdGroupId, adGroupId),

                        // Retrieve only responsive search ads.
                        Predicate.Equals("AdType", AdType.RESPONSIVE_SEARCH_AD.ToString()),
                    },
                    paging = Paging.Default
                };

                AdGroupAdPage page = new AdGroupAdPage();
                try
                {
                    do
                    {
                        // Get the responsive search ads.
                        page = adGroupAdService.get(selector);

                        // Display the results.
                        if (page != null && page.entries != null)
                        {
                            int i = selector.paging.startIndex;

                            foreach (AdGroupAd adGroupAd in page.entries)
                            {
                                ResponsiveSearchAd ad = (ResponsiveSearchAd)adGroupAd.ad;
                                Console.WriteLine(
                                    $"{i + 1} New responsive search ad with ID {ad.id} and " +
                                    $"status {adGroupAd.status} was found.");
                                Console.WriteLine("Headlines:");
                                foreach (AssetLink headline in ad.headlines)
                                {
                                    TextAsset textAsset = headline.asset as TextAsset;
                                    Console.WriteLine($"    {textAsset.assetText}");
                                    if (headline.pinnedFieldSpecified)
                                    {
                                        Console.WriteLine(
                                            $"      (pinned to {headline.pinnedField})");
                                    }
                                }

                                Console.WriteLine("Descriptions:");
                                foreach (AssetLink description in ad.descriptions)
                                {
                                    TextAsset textAsset = description.asset as TextAsset;
                                    Console.WriteLine($"    {textAsset.assetText}");
                                    if (description.pinnedFieldSpecified)
                                    {
                                        Console.WriteLine(
                                            $"      (pinned to {description.pinnedField})");
                                    }
                                }

                                i++;
                            }
                        }

                        selector.paging.IncreaseOffset();
                    } while (selector.paging.startIndex < page.totalNumEntries);

                    Console.WriteLine("Number of responsive search ads found: {0}",
                                      page.totalNumEntries);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get responsive search ads.",
                                                          e);
                }
            }
        }
Ejemplo n.º 30
0
    private static void Init(string szFile, int loadidx = 0)
    {
        TextAsset texAsst = (TextAsset)Resources.Load(szFile);

        if (loadidx == 0)
        {
            if (ltext == null)
            {
                ltext = new List <string>();
            }
            else
            {
                ltext.Clear();
                bInit = false;
            }
        }
        else if (loadidx == 1)
        {
            if (KeyText == null)
            {
                KeyText = new List <string>();
            }
            else
            {
                KeyText.Clear();
                bInit = false;
            }
        }

        if (texAsst != null)
        {
            char[]   charsplit = new char[] { '\r', '\n' };
            string[] token1;
            token1 = texAsst.text.Split(charsplit, System.StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < token1.Length; ++i)
            {
                char[]   charsplit2 = new char[] { ',', '\t' };
                string[] token2     = token1[i].Split(charsplit2, System.StringSplitOptions.RemoveEmptyEntries);
                if (loadidx == 0)
                {
                    if (token2 != null)
                    {
                        ltext.Add(token2[1]);
                    }
                    else
                    {
                        ltext.Add("null");
                    }
                }
                else if (loadidx == 1)
                {
                    if (token2 != null)
                    {
                        KeyText.Add(token2[1]);
                    }
                    else
                    {
                        KeyText.Add("null");
                    }
                }
            }
        }
        bInit = true;
    }
    private async System.Threading.Tasks.Task PushCaliperEventAsync(string json, string pushURL, TextAsset bearerTokenFile)
    {
        if (showDebug)
        {
            Debug.Log(">>>>> Content: " + json);
            Debug.Log(">>>>> Destination: " + pushURL);
        }

        var content = new StringContent(json, Encoding.UTF8, "application/json");         // middleman converting string to HTTPContent

        HttpClient client = new HttpClient();

        if (bearerTokenFile != null)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerTokenFile.text);             // add bearer token header
            if (showDebug)
            {
                Debug.Log(">>>>> Bearer Token Loaded");
            }
        }
        else
        {
            if (showDebug)
            {
                Debug.Log(">>>>> No Bearer Token Path");
            }
        }

        var response = await client.PostAsync(pushURL, content);

        var responseString = await response.Content.ReadAsStringAsync();

        if (showDebug)
        {
            Debug.Log(">>>>> Status: " + response.StatusCode);
            Debug.Log(">>>>> Response: " + responseString);
        }
    }
Ejemplo n.º 32
0
            public void AddAssets()
            {
                if (cla == null)
                {
                    CreateNewCLA();
                }

                OpenFileDialog dlg_open_asset = new OpenFileDialog();
                dlg_open_asset.Filter = "Asset Files|*.png;*.jpg;*.txt|Any Files|*.*";
                dlg_open_asset.Multiselect = true;
                DialogResult result = dlg_open_asset.ShowDialog();
                if (result == DialogResult.Cancel)
                {
                    return;
                }

                foreach (var fileName in dlg_open_asset.FileNames)
                {
                    FileStream stream = File.OpenRead(fileName);
                    if(stream != null)
                    {
                        StreamReader reader = new StreamReader(stream);
                        if(reader != null)
                        {
                            string ext = Path.GetExtension(fileName);

                            if (ext == ".txt")
                            {
                                TextAsset textAsset = new TextAsset();
                                textAsset.SourceFile = fileName;
                                textAsset.Text = reader.ReadToEnd().Replace("\r\n", "\n"); ;

                                AddAsset(textAsset);
                            }
                            else if (ext == ".png" || ext == ".jpg")
                            {
                                Bitmap bitmap = new Bitmap(stream);
                                byte[] textureData = new byte[bitmap.Width * bitmap.Height * 4];
                                BitmapData bitmapData = bitmap.LockBits(Rectangle.FromLTRB(0, 0, bitmap.Width, bitmap.Height),
                                        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                                Marshal.Copy(bitmapData.Scan0, textureData, 0, bitmap.Width * bitmap.Height * 4);
                                bitmap.UnlockBits(bitmapData);

                                TextureAsset textureAsset = new TextureAsset();
                                textureAsset.SourceFile = fileName;
                                textureAsset.Width = bitmap.Width;
                                textureAsset.Height = bitmap.Height;
                                textureAsset.TextureData = textureData;

                                AddAsset(textureAsset, bitmap);
                            }
                        }
                    }
                }
            }
Ejemplo n.º 33
0
    public LevelData LoadData(TextAsset File)
    {
        //the object to return. Look at LevelData.cs for all the variables it can hold
        LevelData retVal = new LevelData();

        //split the file into sections, and run through all of them
        string[] Sections = File.text.Trim().Split('(');
        foreach (string i in Sections)
        {
            //split the name off from the rest of it. The if statement makes sure that there's a closing character
            string[] i2 = i.Trim().Split(')');
            if (i2.Length > 1)
            {
                //check name of section
                switch (i2[0].Trim().ToUpper())
                {
                case "DATA":
                    //function names
                    string[] i3 = i2[1].Trim().Split('{');
                    foreach (string i4 in i3)
                    {
                        //split name off and check for closing character
                        string[] i5 = i4.Trim().Split('}');
                        if (i5.Length > 1)
                        {
                            //check name of function
                            switch (i5[0].Trim().ToUpper())
                            {
                            case "NAME":

                                //split variable/s off, making sure they exist
                                string[] i6a = i5[1].Trim().Split('[');
                                if (i6a.Length > 1)
                                {
                                    //split variable/s off and check for closing character
                                    string[] i7 = i6a[1].Trim().Split(']');
                                    if (i7.Length > 1)
                                    {
                                        //set name
                                        retVal.LevelName = i7[0];
                                    }
                                }
                                break;

                            case "DESCRIPTION":

                                //split variable/s off, making sure they exist
                                string[] i6b = i5[1].Trim().Split('[');
                                if (i6b.Length > 1)
                                {
                                    //split variable/s off and check for closing character
                                    string[] i7 = i6b[1].Trim().Split(']');
                                    if (i7.Length > 1)
                                    {
                                        //set name
                                        retVal.LevelName = i7[0];
                                    }
                                }
                                break;

                            case "MUSIC":

                                //split variable/s off, making sure they exist
                                string[] i6c = i5[1].Trim().Split('[');
                                if (i6c.Length > 1)
                                {
                                    //split variable/s off and check for closing character
                                    string[] i7 = i6c[1].Trim().Split(']');
                                    if (i7.Length > 1)
                                    {
                                        //set music array
                                        retVal.LevelMusic = i7[0].Trim().Split(',');
                                    }
                                }
                                break;

                            case "ICON":

                                //split variable/s off, making sure they exist
                                string[] i6d = i5[1].Trim().Split('[');
                                if (i6d.Length > 1)
                                {
                                    //split variable/s off and check for closing character
                                    string[] i7 = i6d[1].Trim().Split(']');
                                    if (i7.Length > 1)
                                    {
                                        //set name
                                        retVal.Icon = i7[0];
                                    }
                                }
                                break;
                            }
                        }
                    }
                    break;

                case "SCRIPTS":
                    //script package names
                    string[] i3b = i2[1].Split('{');
                    foreach (string i4 in i3b)
                    {
                        //split name off and check for closing character
                        string[] i5 = i4.Split('}');
                        if (i5.Length > 1)
                        {
                            //split script names off, making sure they exist
                            string[] i6 = i5[1].Trim().Split('[');
                            if (i6.Length > 1)
                            {
                                //split script names off and check for closing character
                                string[] i7 = i6[1].Split(']')[0].Trim().Split(',');
                                if (i7.Length > 1)
                                {
                                    string[] i8 = new string[i7.Length + 1];
                                    i8[0] = i5[0].Trim();;
                                    i7.CopyTo(i8, 1);
                                    //add to the script package list
                                    retVal.Scripts.Add(i8);
                                }
                            }
                        }
                    }
                    break;

                case "VISUAL":
                    //internal file names
                    string[] i3c = i2[1].Split('{');
                    foreach (string i4 in i3c)
                    {
                        //split name off and check for closing character
                        string[] i5 = i4.Split('}');
                        if (i5.Length > 1)
                        {
                            //split file name off, making sure it exists
                            string[] i6 = i5[1].Split('[');
                            if (i6.Length > 1)
                            {
                                //split file name off and check for closing character
                                string[] i7 = i6[1].Trim().Split(']');
                                if (i7.Length > 1)
                                {
                                    string[] i8 = new string[] { i5[0].Trim(), i7[0] };
                                    //add to the visual list
                                    retVal.Scripts.Add(i8);
                                }
                            }
                        }
                    }
                    break;

                case "OBJECTS":
                    //script packages on object
                    string[] i3d = i2[1].Split('{');
                    foreach (string i4 in i3d)
                    {
                        //split name off and check for closing character
                        string[] i5 = i4.Split('}');
                        if (i5.Length > 1)
                        {
                            StageObject temp = new StageObject();
                            string[]    i6   = i5[0].Split(',');
                            temp.scripts = new string[i6.Length];
                            for (int i7 = 0; i7 < i6.Length; i7++)
                            {
                                temp.scripts[i7] = i6[i7].Trim();
                            }
                            //split file name off, making sure it exists
                            string[] i8 = i5[1].Split('[');
                            if (i8.Length > 1)
                            {
                                //split file name off and check for closing character
                                string[] i9 = i8[1].Split(']');
                                if (i9.Length > 1)
                                {
                                    string[] i10 = i9[0].Split(';');
                                    foreach (string i11 in i10)
                                    {
                                        string[] i12 = i11.Split(':')[1].Split(',');
                                        switch (i11.Split(':')[0].Trim().ToUpper())
                                        {
                                        //
                                        //PLACE TO ADD MORE FEATURES TO OBJECT LOADING
                                        //
                                        case "XY":
                                            if (i12.Length >= 2)
                                            {
                                                temp.pos = new Vector3(float.Parse(i12[0]), float.Parse(i12[1]), temp.pos.z);
                                            }
                                            break;

                                        case "TLBR":
                                            if (i12.Length >= 4)
                                            {
                                                temp.pos   = new Vector3(float.Parse(i12[0]), float.Parse(i12[1]), temp.pos.z);
                                                temp.scale = new Vector3(float.Parse(i12[2]) - float.Parse(i12[0]), float.Parse(i12[3]) - float.Parse(i12[1]), temp.pos.z);
                                            }
                                            break;

                                        case "TLCBRF":
                                            if (i12.Length >= 6)
                                            {
                                                temp.pos   = new Vector3(float.Parse(i12[0]), float.Parse(i12[1]), float.Parse(i12[2]));
                                                temp.scale = new Vector3(float.Parse(i12[3]) - float.Parse(i12[0]), float.Parse(i12[4]) - float.Parse(i12[1]), float.Parse(i12[5]) - float.Parse(i12[2]));
                                            }
                                            break;

                                        case "LINE2D":
                                            if (i12.Length >= 2)
                                            {
                                                for (int i13 = 0; i13 < i12.Length - 1; i13 += 2)
                                                {
                                                    temp.lineCol.Add(new Vector3(float.Parse(i12[i13]), float.Parse(i12[i13 + 1])));
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    retVal.Objects.Add(temp);
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }
        return(retVal);
    }
Ejemplo n.º 34
0
 public SpriteFont(Platform platform, Engine engine, TextAsset fntUvAsset, TextureAsset fntTexAsset)
 {
     fntUvData = fntUvAsset.Text;
     fntTex = platform.Graphics.CreateTexture (fntTexAsset);
     Init (platform, engine);
 }
    public static void ImportSpineContent(string[] imported, bool reimport = false)
    {
        List <string> atlasPaths    = new List <string>();
        List <string> imagePaths    = new List <string>();
        List <string> skeletonPaths = new List <string>();

        foreach (string str in imported)
        {
            string extension = Path.GetExtension(str).ToLower();
            switch (extension)
            {
            case ".txt":
                if (str.EndsWith(".atlas.txt"))
                {
                    atlasPaths.Add(str);
                }
                break;

            case ".png":
            case ".jpg":
                imagePaths.Add(str);
                break;

            case ".json":
                TextAsset spineJson = (TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset));
                if (IsSpineJSON(spineJson))
                {
                    skeletonPaths.Add(str);
                }
                break;
            }
        }


        List <AtlasAsset> atlases = new List <AtlasAsset>();

        //import atlases first
        foreach (string ap in atlasPaths)
        {
            if (!reimport && CheckForValidAtlas(ap))
            {
                continue;
            }

            TextAsset  atlasText = (TextAsset)AssetDatabase.LoadAssetAtPath(ap, typeof(TextAsset));
            AtlasAsset atlas     = IngestSpineAtlas(atlasText);
            atlases.Add(atlas);
        }

        //import skeletons and match them with atlases
        bool abortSkeletonImport = false;

        foreach (string sp in skeletonPaths)
        {
            if (!reimport && CheckForValidSkeletonData(sp))
            {
                Debug.Log("Automatically skipping: " + sp);
                continue;
            }


            string dir = Path.GetDirectoryName(sp);

            var localAtlases  = FindAtlasesAtPath(dir);
            var requiredPaths = GetRequiredAtlasRegions(sp);
            var atlasMatch    = GetMatchingAtlas(requiredPaths, localAtlases);

            if (atlasMatch != null)
            {
                IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
            }
            else
            {
                bool resolved = false;
                while (!resolved)
                {
                    int result = EditorUtility.DisplayDialogComplex("Skeleton JSON Import Error!", "Could not find matching AtlasAsset for " + Path.GetFileNameWithoutExtension(sp), "Select", "Skip", "Abort");
                    switch (result)
                    {
                    case -1:
                        Debug.Log("Select Atlas");
                        AtlasAsset selectedAtlas = GetAtlasDialog(Path.GetDirectoryName(sp));
                        if (selectedAtlas != null)
                        {
                            localAtlases.Clear();
                            localAtlases.Add(selectedAtlas);
                            atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
                            if (atlasMatch != null)
                            {
                                resolved = true;
                                IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
                            }
                        }

                        break;

                    case 0:
                        var atlasList = MultiAtlasDialog(requiredPaths, Path.GetDirectoryName(sp), Path.GetFileNameWithoutExtension(sp));

                        if (atlasList != null)
                        {
                            IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasList.ToArray());
                        }

                        resolved = true;
                        break;

                    case 1:
                        Debug.Log("Skipped importing: " + Path.GetFileName(sp));
                        resolved = true;
                        break;


                    case 2:
                        //abort
                        abortSkeletonImport = true;
                        resolved            = true;
                        break;
                    }
                }
            }

            if (abortSkeletonImport)
            {
                break;
            }
        }

        //TODO:  any post processing of images
    }
    // Use this for initialization
    void Start()
    {
        Debug.Log ("Llamado al metodo START de MenuOfStepsPhase2 - Instancia:" + this.gameObject.GetInstanceID() + " name:" + this.gameObject.name);

        //inicializando variable que controla si todos los items estan en los slots:
        items_ubicados_correctamente = false;

        //inicializando la variable que indica si se ha pedido organizar automaticamente los pasos
        //por el appmanager:
        //steps_organized_from_manager = false;

        //desactivando el tick de orden correcto hasta que se obtenga el orden correcto:
        if (tickCorrectOrder != null)
            tickCorrectOrder.enabled = false;

        //cargando la imagen del tick y del boton warning:
        img_tick = Resources.Load<Sprite> ("Sprites/buttons/tick");
        img_warning = Resources.Load<Sprite> ("Sprites/buttons/warning_order");

        //obteniendo el componente del encabezado de la imagen:
        imagen_header = GameObject.Find ("header_image_menuphase2_eval");
        if (imagen_header != null) {
            Debug.Log ("La imagen del HEADER es: " + image_header_phase1);
            sprite_image_header_phase1 = Resources.Load<Sprite> (image_header_phase1);
            imagen_header.GetComponent<Image>().sprite = sprite_image_header_phase1;
        }

        //obteniendo el componente text que se llama titulo en el prefab:
        //titulo_object = GameObject.Find ("title_menu_steps_phase2_text_eval");
        if (titulo_object != null) {
            Debug.LogError ("Se va a cambiar el TITULO de la interfaz es: " + titulo);
            titulo_object.GetComponent<Text> ().text = titulo;
        } else {
            Debug.LogError("Error: No se encuentra el objeto TITULO para la interfaz en MenuOfStepsPhaseTwoManagerEval");
        }

        //colocando el texto de la introduccion:
        //introduction_object = GameObject.Find ("introduction_steps_of_phase1_interface");
        if (introduction_object != null) {
            Debug.LogError ("Se va a cambiar el texto de la INTRODUCCION");
            introduction_asset = Resources.Load (introduction_text_path) as TextAsset;
            introduction_object.GetComponent<Text> ().text = introduction_asset.text;
        } else {
            Debug.LogError("Error: No se encuentra el objeto INTRODUCCION para la interfaz en MenuOfStepsPhaseTwoManagerEval");
        }

        //accion regresar en el boton
        if(regresar != null){
            Debug.LogError("Se agrega la accion al boton REGRESAR");
            regresar.onClick.AddListener(()=>{ActionButton_goBackToMenuPhases();});
        }

        //accion ir al Step1 del Phase

        //colocando las imagenes de las fases despues del encabezado (guia del proceso completo para los estudiantes)
        //image_phase1_object = GameObject.Find ("image_phase1");
        if (image_phase1_object != null) {
            image_phase1_sprite = Resources.Load<Sprite> (image_phase1_path);
            image_phase1_object.GetComponent<Image> ().sprite = image_phase1_sprite;
        } else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        //image_phase2_object = GameObject.Find ("image_phase2");
        if (image_phase2_object != null) {
            image_phase2_sprite = Resources.Load<Sprite>(image_phase2_path);
            image_phase2_object.GetComponent<Image>().sprite = image_phase2_sprite;
        }else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        //image_phase3_object = GameObject.Find ("image_phase3");
        if (image_phase3_object != null) {
            image_phase3_sprite = Resources.Load<Sprite>(image_phase3_path);
            image_phase3_object.GetComponent<Image>().sprite = image_phase3_sprite;
        }else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        //image_phase4_object = GameObject.Find ("image_phase4");
        if (image_phase4_object != null) {
            image_phase4_sprite = Resources.Load<Sprite>(image_phase4_path);
            image_phase4_object.GetComponent<Image>().sprite = image_phase4_sprite;
        }else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        //image_phase5_object = GameObject.Find ("image_phase5");
        if (image_phase5_object != null) {
            image_phase5_sprite = Resources.Load<Sprite>(image_phase5_path);
            image_phase5_object.GetComponent<Image>().sprite = image_phase5_sprite;
        }else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        //image_phase6_object = GameObject.Find ("image_phase6");
        if (image_phase6_object != null) {
            image_phase6_sprite = Resources.Load<Sprite>(image_phase6_path);
            image_phase6_object.GetComponent<Image>().sprite = image_phase6_sprite;
        }else {
            Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval");
        }

        if (btn_one_to_order != null) {
            image_button_sprite_uno = Resources.Load<Sprite> (img_one_to_order);
            btn_one_to_order.GetComponent<Image>().sprite = image_button_sprite_uno;
            ////Agregando la accion para ir al step1 - phase 1 (buscar capo del carro):
            btn_one_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnOne();});
            drag_controller = btn_one_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_one;
        }

        if (btn_two_to_order != null) {
            image_button_sprite_dos = Resources.Load<Sprite> (img_two_to_order);
            btn_two_to_order.GetComponent<Image>().sprite = image_button_sprite_dos;
            //Agregando la accion para ir al conjunto de actividades (2. limpieza):
            btn_two_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnTwo();});
            drag_controller = btn_two_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_two;
        }

        if (btn_three_to_order != null) {
            image_button_sprite_tres = Resources.Load<Sprite> (img_three_to_order);
            btn_three_to_order.GetComponent<Image>().sprite = image_button_sprite_tres;
            //Agregando la accion para ir al conjunto de actividades (3. secado):
            btn_three_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnThree();});
            drag_controller = btn_three_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_three;
        }

        if (btn_four_to_order != null) {
            image_button_sprite_cuatro = Resources.Load<Sprite> (img_four_to_order);
            btn_four_to_order.GetComponent<Image>().sprite = image_button_sprite_cuatro;
            //Agregando la accion para ir al conjunto de actividades (4. localizar irregularidades):
            btn_four_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnFour();});
            drag_controller = btn_four_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_four;
        }

        if (btn_five_to_order != null) {
            image_button_sprite_cinco = Resources.Load<Sprite> (img_five_to_order);
            btn_five_to_order.GetComponent<Image>().sprite = image_button_sprite_cinco;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            btn_five_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnFive();});
            drag_controller = btn_five_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_five;
        }

        if (btn_six_to_order != null) {
            image_button_sprite_seis = Resources.Load<Sprite> (img_six_to_order);
            btn_six_to_order.GetComponent<Image>().sprite = image_button_sprite_seis;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            btn_six_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnSix();});
            drag_controller = btn_six_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_six;
        }

        if (btn_seven_to_order != null) {
            image_button_sprite_siete = Resources.Load<Sprite> (img_seven_to_order);
            btn_seven_to_order.GetComponent<Image>().sprite = image_button_sprite_siete;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            btn_seven_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnSeven();});
            drag_controller = btn_seven_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_seven;
        }

        if (btn_eight_to_order != null) {
            image_button_sprite_ocho = Resources.Load<Sprite> (img_eight_to_order);
            btn_eight_to_order.GetComponent<Image>().sprite = image_button_sprite_ocho;
            //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades):
            btn_eight_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnEight();});
            drag_controller = btn_eight_to_order.GetComponent<DragBehaviourMenuOfSteps>();
            if(drag_controller != null)
                drag_controller.phase_number = step_number_btn_eight;
        }

        //colocando los textos en los botones:
        if(text_btn_one_to_order != null){
            text_btn_one_to_order.text = this.string_btn_one_text;
        }

        if(text_btn_two_to_order != null){
            text_btn_two_to_order.text = this.string_btn_two_text;
        }

        if(text_btn_three_to_order != null){
            text_btn_three_to_order.text = this.string_btn_three_text;
        }

        if(text_btn_four_to_order != null){
            text_btn_four_to_order.text = this.string_btn_four_text;
        }

        if(text_btn_five_to_order != null){
            text_btn_five_to_order.text = this.string_btn_five_text;
        }

        if(text_btn_six_to_order != null){
            text_btn_six_to_order.text = this.string_btn_six_text;
        }

        if(text_btn_seven_to_order != null){
            text_btn_seven_to_order.text = this.string_btn_seven_text;
        }

        if(text_btn_eight_to_order != null){
            text_btn_eight_to_order.text = this.string_btn_eight_text;
        }

        //llamado al metodo hasChanged para verificar si hay algun cambio los slots de pasos:
        HasChanged ();
    }
Ejemplo n.º 37
0
            public void ReadFrom(BinaryReader reader)
            {
                block.ReadFrom(reader);

                List<AssetData> tempAssets = new List<AssetData>();

                int count = reader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    AssetClass type = (AssetClass)reader.ReadByte();
                    AssetData asset = null;
                    switch (type)
                    {
                        case AssetClass.TEXT:
                            asset = new TextAsset();
                            break;
                        case AssetClass.TEXTURE:
                            asset = new TextureAsset();
                            break;
                        case AssetClass.REFERENCE:
                            asset = new ReferenceAsset();
                            break;
                    }

                    if (asset != null)
                    {
                        asset.headerBlock.ReadFrom(reader);
                        tempAssets.Add(asset);
                    }
                }
                foreach (var asset in tempAssets)
                {
                    asset.dataBlock.ReadFrom(reader);
                }
                foreach (var asset in tempAssets)
                {
                    if (asset.Type() == AssetClass.TEXT)
                    {
                        program.AddAsset(asset);
                    }
                    else
                    {
                        TextureAsset texture = (TextureAsset)asset;
                        Bitmap bitmap = null;
                        using (var ms = new MemoryStream(texture.TextureData))
                        {
                            bitmap = new Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                            var bitmapData = bitmap.LockBits(Rectangle.FromLTRB(0, 0, texture.Width, texture.Height),
                                ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                            Marshal.Copy(texture.TextureData, 0, bitmapData.Scan0, texture.Length());
                            bitmap.UnlockBits(bitmapData);

                            program.AddAsset(asset, bitmap);
                        }
                    }
                }
            }